Question

I need to generate a xml file that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<ns:Root xmlns:ns0="http://namespace">
  <Node1>
    <A>ValueA</A>
    <B>ValueB</B>
  </Node1>
</Root>

This is my code:

const string ns = "http://namespace";
var xDocument = new XDocument(
    new XElement("Root",
        new XAttribute(XNamespace.Xmlns + "ns0", ns),
        new XElement("Node1",
            new XElement("A", "ValueA"),
            new XElement("B", "ValueB")
        )
    )
);

But this produces:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:ns0="http://namespace">
  <Node1>
    <A>ValueA</A>
    <B>ValueB</B>
  </Node1>
</Root>

Note the missing "ns0:" before the Root node. How can I add it? Everything else should be exactly the same.

Was it helpful?

Solution

Try This

XNamespace ns = XNamespace.Get("http://namespace");

var xDocument = new XDocument(
                new XElement(ns + "Root",
                    new XAttribute(XNamespace.Xmlns + "ns0", ns),
                    new XElement("Node1",
                        new XElement("A", "ValueA"),
                        new XElement("B", "ValueB")
                        )));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top