How do I add multiple Namespace declarations to an XDocument?
Asked Answered
R

2

35

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?

Ricciardi answered 12/8, 2009 at 10:25 Comment(0)
L
60

Do you mean:

new XAttribute(XNamespace.Xmlns + "ns4", ns4),
new XAttribute(XNamespace.Xmlns + "ns3", ns3),
new XAttribute(XNamespace.Xmlns + "ns2", ns2),
Longueur answered 12/8, 2009 at 10:28 Comment(1)
Looks like it! Thanks for the extremely quick response.Ricciardi
V
0

Here xmldoc is Xdocument object. The existing namespace is removed and two new ones added.

//remove existing xmlns xmlDoc.Root.Descendants().Attributes().Where(x => x.IsNamespaceDeclaration).Remove(); foreach (var elem in xmlDoc.Descendants()) elem.Name = elem.Name.LocalName;

        //Add new xmlns
        XNamespace ns1 = @"www.google.com";
        XNamespace ns2 = @"http://www.w3.org/2001/XMLSchema-instance";

        List<XAttribute> lst = new List<XAttribute>();
        lst.Add(new XAttribute(XNamespace.Xmlns + "nm", ns1));
        lst.Add(new XAttribute(XNamespace.Xmlns + "pf", ns2));

        xmlDoc.Root.Add(lst);
Vicariate answered 17/7, 2023 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.