C# 如何使用XmlDocument编写xsd:schema标记

C# 如何使用XmlDocument编写xsd:schema标记,c#,xml,xsd,C#,Xml,Xsd,我正在尝试以编程方式编写XML文档 我需要在我的文档中添加标记 目前我有: var xmlDoc = new XmlDocument(); var root = xmlDoc.CreateElement("root"); xmlDoc.AppendChild(root); var xsdSchemaElement = xmlDoc.CreateElement("schema"); xsdSchemaElement.Prefix = "xsd"; xsdSchemaElement.SetAtt

我正在尝试以编程方式编写XML文档

我需要在我的文档中添加
标记

目前我有:

var xmlDoc = new XmlDocument();

var root = xmlDoc.CreateElement("root");
xmlDoc.AppendChild(root);

var xsdSchemaElement = xmlDoc.CreateElement("schema");
xsdSchemaElement.Prefix = "xsd";
xsdSchemaElement.SetAttribute("id", "root");

root.AppendChild(xsdSchemaElement);
然而,这导致:

<root>
  <schema id="root" />
</root>

它被称为like
xmlDoc.Schemas.Add(GetTheSchema(xmlDoc))
但不会在我的目标
XML

中生成任何内容。使用LINQ to XML,您可以将
XElement
s和
XAttributes
s嵌套在特定的层次结构中,以构造XML文档。至于名称空间前缀,您可以使用
XNamespace

请注意,在您的情况下,每个名称空间前缀(如
xsd
)在使用之前都必须声明,例如
xmlns:xsd=”http://www.w3.org/2001/XMLSchema“

输出:

<root xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:schema id="root" />
</root>

使用LINQ to XML,您可以将
XElement
s和
XAttributes
s嵌套在特定的层次结构中,以构建XML文档。至于名称空间前缀,您可以使用
XNamespace

请注意,在您的情况下,每个名称空间前缀(如
xsd
)在使用之前都必须声明,例如
xmlns:xsd=”http://www.w3.org/2001/XMLSchema“

输出:

<root xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:schema id="root" />
</root>


XmlDocument有一个名为Schemas的属性。您是否尝试在那里添加架构定义?使用
xmlDoc.Schemas.Add(GetMySchema(xmlDoc))
不会引发任何异常,也不会将任何xml写入目标文件。您知道如何使用
XmlSchema
吗?@KingKerosin您能使用LINQ-to-XML而不是
XmlDocument
?@har07是的。只要读一读,从
XDocument
开始比
XmlDocument
好得多。关于这方面有什么好的教程吗?@KingKerosin我没有任何具体的教程可以推荐。下面是一些您可以学习的示例:,XmlDocument有一个名为Schemas的属性。您是否尝试在那里添加架构定义?使用
xmlDoc.Schemas.Add(GetMySchema(xmlDoc))
不会引发任何异常,也不会将任何xml写入目标文件。您知道如何使用
XmlSchema
吗?@KingKerosin您能使用LINQ-to-XML而不是
XmlDocument
?@har07是的。只要读一读,从
XDocument
开始比
XmlDocument
好得多。关于这方面有什么好的教程吗?@KingKerosin我没有任何具体的教程可以推荐。以下是一些您可以学习的示例:,
<root xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:schema id="root" />
</root>