Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create XElement with specific namespace?

I have problem with creating new element in LinqToXml. This is my code:

XNamespace xNam = "name"; 
XNamespace _schemaInstanceNamespace = @"http://www.w3.org/2001/XMLSchema-instance";

XElement orderElement = new XElement(xNam + "Example",
                  new XAttribute(XNamespace.Xmlns + "xsi", _schemaInstanceNamespace));

I want to get this:

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

But in XML I always get this:

<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="name">

What I'm doing wrong?

like image 903
GrzesiekO Avatar asked Aug 21 '12 07:08

GrzesiekO


People also ask

How to create XML namespace in c#?

To create an element or an attribute that's in a namespace, you first declare and initialize an XNamespace object. You then use the addition operator overload to combine the namespace with the local name, expressed as a string. The following example creates a document with one namespace.

How do I add a namespace to an XML file?

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

How do you make XElement?

var el = new XElement("name", value);


1 Answers

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> is not namespace well-formed as the prefix name is not declared. So constructing that with an XML API is not possible. What you can do is construct the following namespace well-formed XML

<name:Example xmlns:name="http://example.com/name" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />

with the code

//<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="http://example.com/name"></name:Example>

XNamespace name = "http://example.com/name";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

XElement example = new XElement(name + "Example",
new XAttribute(XNamespace.Xmlns + "name", name),
new XAttribute(XNamespace.Xmlns + "xsi", xsi));

Console.WriteLine(example);
like image 174
Martin Honnen Avatar answered Sep 18 '22 18:09

Martin Honnen