Home >Backend Development >C++ >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>
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.
Answer: Using LINQ to XML, we can easily add namespaces to elements.
XNamespace ns = "sphinx"; XElement element = new XElement(ns + "docset");
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"))));
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>
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!