简体   繁体   中英

How to specify an xmlns for XDocument?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM