Search code examples
c#xmlxsdxelement

Write reference to xsd/schema in output from XElement.Save()


In C#, assume that I have an XElement (say myXElement) containing some XML structure. By calling

   myXElement.Save("/path/to/myOutput.xml");

the XML is written to a text file. However, I would like this textfile to include a reference to a (local) xsd-file (an XML schema). That is, I would like the output to look something like this...

<?xml version="1.0" encoding="utf-8" ?>
<MyElement
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="MySchema.xsd">
...

How can I do this?


Solution

  • On the root element, just add an attribute:

    Example 1:

    XmlDocument d = new XmlDocument();
    XmlElement e = d.CreateElement("MyElement");
    XmlAttribute a = d.CreateAttribute("xsi", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
    
    a.Value = "MySchema.xsd";
    
    d.AppendChild(e);
    e.Attributes.Append(a);
    

    Example 2:

    XDocument d = new XDocument();
    XElement e = new XElement("MyElement");
    XAttribute a = new XAttribute(XName.Get("noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance"), "MySchema.xsd");
    
    d.Add(e);
    e.Add(a);