1

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.

sventevit
  • 4,766
  • 10
  • 57
  • 89
  • Have you tried to put `"ns:Root"` instead `"Root"` as parameter of first `XElement` constructor? – HuorSwords Jul 12 '13 at 09:40
  • 1
    @HuorSwords: does not work, I get "The ':' character, hexadecimal value 0x3A, cannot be included in a name" exception. – sventevit Jul 12 '13 at 09:42
  • Please, check this [answer](http://stackoverflow.com/a/6125645/982431) for a similar (even not equal) question. – HuorSwords Jul 12 '13 at 09:45

1 Answers1

1

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")
                        )));
Rakesh
  • 310
  • 3
  • 19