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.
XML Namespaces - The xmlns Attribute When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".
the xmlns attribute specifies the xml namespace for a document. This basically helps to avoid namespace conflicts between different xml documents, if for instance a developer mixes xml documents from different xml applications.
In the attribute xmlns:pfx, xmlns is like a reserved word, which is used only to declare a namespace. In other words, xmlns is used for binding namespaces, and is not itself bound to any namespace. Therefore, the above example is read as binding the prefix "pfx" with the namespace "http://www.foo.com."
The namespace URI is what allows us to identify uniquely the namespace. It is also called the namespace name. If you use an URL, you will take advantage of the uniqueness of domain names in the domain name system (DNS).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With