XElement Namespaces
This guide demonstrates how to create XML documents with node prefixes using XElement.
Creating XML Documents with Node Prefix
To create XML documents with node prefix, use the following steps:
XNamespace ns = "http://url/for/sphinx";
XElement element = new XElement(ns + "docset");
Handling Exception
If you encounter the exception "System.Xml.XmlException: The ':' character, hexadecimal val..." when trying to create an element with a namespace prefix, ensure that you are using the namespace in the correct format. Use the GetNamespacePrefix method to retrieve the correct prefix for the provided namespace, as shown below:
XNamespace ns = XNamespace.Get("http://url/for/sphinx"); XElement element = new XElement(ns.GetNamespacePrefix() + "docset");
Creating Complex XML Documents
To create more complex XML documents with nested elements and attributes, you can use the following example:
XNamespace ns = "http://url/for/sphinx"; XElement container = 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 following XML document:
<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 Use XElement to Create XML Documents with Namespaces and Prefixes?. For more information, please follow other related articles on the PHP Chinese website!