Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 302
ispiro Avatar asked Feb 12 '13 19:02

ispiro


People also ask

How do I include xmlns in XML?

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".

What is the xmlns attribute?

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.

What is xmlns in XML schema?

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."

What is xmlns URI?

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).


1 Answers

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.

like image 157
codekaizen Avatar answered Oct 25 '22 03:10

codekaizen