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?
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.
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".
var el = new XElement("name", value);
<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);
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