15

I tried:

textBox1.Text = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
    new XElement("root1", new XAttribute( "xmlns", @"http://example.com"), new XElement("a", "b"))
).ToString();

But I get:

The prefix '' cannot be redefined from '' to 'http://example.com' within the same start element tag.

I also tried substituting (according to an answer I found) :

XAttribute(XNamespace.Xmlns,...

But got an error as well.

Note: I'm not trying to have more than one xmlns in the document.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
ispiro
  • 26,556
  • 38
  • 136
  • 291

1 Answers1

29

The way the XDocument API works with namespace-scoped names is as XName instances. These are fairly easy to work with, as long as you accept that an XML name isn't just a string, but a scoped identifier. Here's how I do it:

var ns = XNamespace.Get("http://example.com");
var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
var root = new XElement(ns + "root1", new XElement(ns + "a", "b"));
doc.Add(root);

Result:

<root1 xmlns="http://example.com">
    <a>b</a>
</root1>

Note the + operator is overloaded to accept an XNamespace and a String to result in and XName instance.

codekaizen
  • 26,990
  • 7
  • 84
  • 140
  • 2
    Thanks. It seems strange that there won't be a _simple_ way to add a namespace only once. – ispiro Feb 12 '13 at 20:50
  • 1
    Well, I think this is fairly simple, and it really drives home that what you are doing is creating namespaced names, not just strings. If you want less code for namespaces, the `System.Xml.XmlDocument` class uses a Namespace manager to keep track of the root namespace, and you can pretend like it doesn't exist once you get it setup right. – codekaizen Feb 12 '13 at 20:53
  • See my next question: http://stackoverflow.com/questions/14841517/how-can-i-add-innerxml-without-it-being-modified-in-any-way - I'm trying `XmlDocument` as well and it's not helping. – ispiro Feb 12 '13 at 20:55
  • For me this does not add the xmlns to my root1 equivalent but instead to every single descendant - is there a way to add it just as xmlns instead? – Sam Jan 28 '14 at 13:59
  • 2
    @Sam - If all the child elements have the same namespace, then when you convert the XML document to a string, the output mechanism can optionally elide the namespace declaration on child elements. So, if you're seeing `xmlns` on the child elements, check how you're outputting it. Additionally, the presence of the namespace attribute on elements should not affect the actual meaning of the XML document. – codekaizen Jan 28 '14 at 17:09
  • 1
    Yup, after some fiddling around I managed to add the Namespace in a way which made the output mechanism work like I wanted it to. – Sam Jan 30 '14 at 09:25