Adding xmlns namespace to Xdocument

I want to create an XDocument with what will look like below:

<configurations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://msn.com/csl/featureConfigurationv2">
  <configuration>
    …
  </configuration>
</configurations>

I have to deal with the problem of adding a second attribute. I try this:

XYZ.Element("configurations").SetAttributeValue("xmlns", "http://msn.com/csl/featureConfigurationv2");

But it does not add an attribute.

Can you suggest something else please.

+5
source share
1 answer

Try this way

XNamespace ns = XNamespace.Get("http://msn.com/csl/featureConfigurationv2"); 
XDocument doc = new XDocument(
    // Do XDeclaration Stuff
    new XElement("configurations",
        new XAttribute(XNamespace.Xmlns, ns),
        // Do XElement Stuff
     )
);

and this way too

XNamespace ns = "http://msn.com/csl/featureConfigurationv2";
XElement configurations = new XElement(ns + "configurations",
    new XAttribute("xmlns", "http://msn.com/csl/featureConfigurationv2"),
    // Do XElement Stuff
);
+1
source

All Articles