C# 在XElement.Save()的输出中写入对xsd/schema的引用

C# 在XElement.Save()的输出中写入对xsd/schema的引用,c#,xml,xsd,xelement,C#,Xml,Xsd,Xelement,在C#中,假设我有一个XElement(比如myXElement)包含一些XML结构。打电话 myXElement.Save("/path/to/myOutput.xml"); XML被写入文本文件。但是,我希望这个文本文件包含对(本地)xsd文件(XML模式)的引用。也就是说,我希望输出像这样 <?xml version="1.0" encoding="utf-8" ?> <MyElement xmlns:xsi="http://www.w3.org/2001/X

在C#中,假设我有一个
XElement
(比如
myXElement
)包含一些XML结构。打电话

   myXElement.Save("/path/to/myOutput.xml");
XML被写入文本文件。但是,我希望这个文本文件包含对(本地)xsd文件(XML模式)的引用。也就是说,我希望输出像这样

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

...

如何执行此操作?

在根元素上,只需添加一个属性:

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

在根元素上,只需添加一个属性:

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

您应该使用XDocument而不是XElement,因为它包含获取和设置XML声明等的方法

您应该使用XDocument而不是XElement,因为它包含获取和设置XML声明等的方法

我使用的是XElement和XDocument,而不是XmlElement或XmlDocument,因此(对我而言)不清楚如何应用您的代码。我使用的是XElement和XDocument,而不是XmlElement或XmlDocument,因此(对我而言)不清楚如何应用您的代码。