13

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?

GrzesiekO
  • 1,179
  • 4
  • 21
  • 34

1 Answers1

21

<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);
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • 2
    I forgot write about this. Namespace name is declared in parent node. After creating xml I always validate this on some xml validator. – GrzesiekO Aug 21 '12 at 10:53