Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add multiple Namespace declarations to an XDocument?

I'm using an XDocument to build an Xml document in a known structure. The structure I am trying to build is as follows:

<request xmlns:ns4="http://www.example.com/a" xmlns:ns3="http://www.example.com/b" xmlns:ns2="http://www.example.com/c" >     <requestId>d78d4056-a831-4c7d-a357-d14402f623fc</requestId>     .... </request> 

Notice the "xmlns:nsX" attributes.

I am trying, without success, to add these attributes to my "request" element.

XNamespace ns4 = XNamespace.Get("http://www.example.com/a"); XNamespace ns3 = XNamespace.Get("http://www.example.com/b"); XNamespace ns2 = XNamespace.Get("http://www.example.com/c");  XDocument doc = new XDocument(     new XDeclaration("1.0", "utf-8", "no"),     new XElement("request",         new XAttribute("ns4", ns4),         new XAttribute("ns3", ns3),         new XAttribute("ns2", ns2),         new XElement("requestId", Guid.NewGuid())      ) ); 

However, this produces the following:

<request ns4="http://www.example.com/a" ns3="http://www.example.com/b" ns2="http://www.example.com/c">   <requestId>38b07cfb-5e41-4d9a-97c8-4740c0432f11</requestId> </request> 

How do I add the namespace declarations correctly?

like image 578
Paul Suart Avatar asked Aug 12 '09 10:08

Paul Suart


People also ask

Can XML have multiple namespaces?

When you use multiple namespaces in an XML document, you can define one namespace as the default namespace to create a cleaner looking document. The default namespace is declared in the root element and applies to all unqualified elements in the document. Default namespaces apply to elements only, not to attributes.

How do I add a namespace to an XML file?

XML Namespaces - The xmlns Attribute When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

How do I change the default namespace in XML?

You can change the default namespace within a particular element by adding an xmlns attribute to the element. Example 4-4 is an XML document that initially sets the default namespace to http://www.w3.org/1999/xhtml for all the XHTML elements. This namespace declaration applies within most of the document.

Which are the namespaces in .NET used for XML?

The default namespace is used in the XML document to save you from using prefixes in all the child elements. The only difference between default namespace and a simple namespace is that: There is no need to use a prefix in default namespace.


1 Answers

Do you mean:

new XAttribute(XNamespace.Xmlns + "ns4", ns4), new XAttribute(XNamespace.Xmlns + "ns3", ns3), new XAttribute(XNamespace.Xmlns + "ns2", ns2), 
like image 189
Marc Gravell Avatar answered Oct 05 '22 18:10

Marc Gravell