user2273044
user2273044

Reputation: 161

C# with XDocument and xsi:schemaLocation

I want to create the following XML.

<?xml version="1.0" encoding="utf-8"?>
<MyNode xsi:schemaLocation="https://MyScheme.com/v1-0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://MyScheme.com/v1-0 Sscheme.xsd">
  <MyInfo>
    <MyNumber>string1</MyNumber>
    <MyName>string2</MyName>
    <MyAddress>string3</MyAddress>
  </MyInfo>
  <MyInfo2>
    <FirstName>string4</FirstName>
  </MyInfo2>
</MyNode>

I'm using this code.

    XNamespace xmlns = "https://MyScheme.com/v1-0 Sscheme.xsd";
    XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
    XNamespace schemaLocation = XNamespace.Get("https://MyScheme.com/v1-0");

    XDocument xmlDocument = new XDocument(
         new XElement(xmlns + "MyNode",
             new XAttribute(xsi + "schemaLocation", schemaLocation),
             new XAttribute(XNamespace.Xmlns + "xsi", xsi),
             new XElement("MyInfo",
                 new XElement("MyNumber", "string1"),
                 new XElement("MyName", "string2"),
                 new XElement("MyAddress", "string3")
                 ),
                 new XElement("MyInfo2",
                     new XElement("FirstName", "string4")
                     )
         )
     );
    xmlDocument.Save("C:\\MyXml.xml");

However, I'm getting xmlns="" inside tags MyInfo and MyInfo2.

Can somebody help me to create the correct XML?

Upvotes: 0

Views: 1441

Answers (1)

har07
har07

Reputation: 89305

You need to use xmlns XNamespace for all elements, because that is default namespace and it is declared at root level element. Note that descendant elements inherit ancestor default namespace implicitly, unless otherwise specified :

XDocument xmlDocument = new XDocument(
         new XElement(xmlns + "MyNode",
             new XAttribute(xsi + "schemaLocation", schemaLocation),
             new XAttribute(XNamespace.Xmlns + "xsi", xsi),
             new XElement(xmlns+"MyInfo",
                 new XElement(xmlns+"MyNumber", "string1"),
                 new XElement(xmlns+"MyName", "string2"),
                 new XElement(xmlns+"MyAddress", "string3")
                 ),
                 new XElement(xmlns+"MyInfo2",
                     new XElement(xmlns+"FirstName", "string4")
                     )
         )
     ); 

Dotnetfiddle Demo

Upvotes: 1

Related Questions