Home > Backend Development > C++ > How to Generate XML Documents with Prefixed Nodes using XElement?

How to Generate XML Documents with Prefixed Nodes using XElement?

Barbara Streisand
Release: 2024-12-30 06:27:11
Original
249 people have browsed it

How to Generate XML Documents with Prefixed Nodes using XElement?

XML Namespace Prefixes in XElement

Creating XML documents with node prefixes can be challenging using XElement. This question explores how to handle prefixed namespaces when using XElement.

Question: How can we generate XML documents with prefixed nodes like this example?

<sphinx:docset>
  <sphinx:schema>
    <sphinx:field name="subject"/>
    <sphinx:field name="content"/>
    <sphinx:attr name="published" type="timestamp"/>
 </sphinx:schema>
</sphinx:docset>
Copy after login

Exception: Using new XElement("sphinx:docset") throws an exception:

Unhandled Exception: System.Xml.XmlException: The ':' character, hexadecimal val
  ue 0x3A, cannot be included in a name.
Copy after login

Answer: Using LINQ to XML, we can easily add namespaces to elements.

XNamespace ns = "sphinx";
XElement element = new XElement(ns + "docset");
Copy after login

To define aliases like in the example, use the following:

XNamespace ns = "http://url/for/sphinx";
XElement element = new XElement("container",
    new XAttribute(XNamespace.Xmlns + "sphinx", ns),
    new XElement(ns + "docset",
        new XElement(ns + "schema"),
            new XElement(ns + "field", new XAttribute("name", "subject")),
            new XElement(ns + "field", new XAttribute("name", "content")),
            new XElement(ns + "attr", 
                         new XAttribute("name", "published"),
                         new XAttribute("type", "timestamp"))));
Copy after login

This code will produce the desired XML structure:

<container xmlns:sphinx="http://url/for/sphinx">
  <sphinx:docset>
    <sphinx:schema />
    <sphinx:field name="subject" />
    <sphinx:field name="content" />
    <sphinx:attr name="published" type="timestamp" />
  </sphinx:docset>
</container>
Copy after login

The above is the detailed content of How to Generate XML Documents with Prefixed Nodes using XElement?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template