开发者

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开发者_JAVA百科...

<?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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜