someName
someName

Reputation: 1273

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?

Upvotes: 2

Views: 1328

Answers (3)

Bill Menees
Bill Menees

Reputation: 2464

This extends Josh M.'s answer to use the xsi prefix with XElement as requested. XElement.GetNamespaceOfPrefix must be used; otherwise, XElement will assign its own prefix like p1.

XDocument d = new();
XElement e = new("MyElement");
XAttribute xsi = new(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance");
d.Add(e);
e.Add(xsi);
XAttribute noNs = new(e.GetNamespaceOfPrefix("xsi")!.GetName("noNamespaceSchemaLocation"), "MySchema.xsd");
e.Add(noNs);

Calling d.Save("MyDocument.xml"); produces:

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

Upvotes: 0

Josh M.
Josh M.

Reputation: 27831

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);

Upvotes: 2

James Walford
James Walford

Reputation: 2953

You should use XDocument instead of XElement as this contains methods for getting and setting the XML declaratuion etc http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx

Upvotes: 0

Related Questions