How create XElement with specific namespace?
16,537
<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);
Comments
-
GrzesiekO almost 2 years
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 over 11 yearsI forgot write about this. Namespace name is declared in parent node. After creating xml I always validate this on some xml validator.