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?

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
Paul Suart
  • 6,505
  • 7
  • 44
  • 65

2 Answers2

60

Do you mean:

new XAttribute(XNamespace.Xmlns + "ns4", ns4),
new XAttribute(XNamespace.Xmlns + "ns3", ns3),
new XAttribute(XNamespace.Xmlns + "ns2", ns2),
Adan Sandoval
  • 436
  • 1
  • 6
  • 18
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
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);
subho
  • 79
  • 2
  • 12