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

时间:2016-04-14 07:37:20

标签: c# xml xsd

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

我需要在文档中添加<xsd:schema>标记。

目前我有:

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>

如何将代码设为<xsd:schema>

已经尝试过var xsdSchemaElement = xmlDoc.CreateElement("xsd:schema");而忽略了xsd:

编辑#1

添加方法

private static XmlSchema GetTheSchema(XmlDocument xmlDoc)
{
    var schema = new XmlSchema();
    schema.TargetNamespace = "xsd";
    return schema;
}

被称为xmlDoc.Schemas.Add(GetTheSchema(xmlDoc));,但不会在我的目标XML中生成任何内容。

1 个答案:

答案 0 :(得分:0)

使用LINQ-to-XML,您可以将XElementXAttributes嵌套在某个层次结构中以构建XML文档。对于名称空间前缀,您可以使用XNamespace

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

XNamespace xsd = "http://www.w3.org/2001/XMLSchema";
var doc = 
    new XDocument(
        //root element 
        new XElement("root",
            //namespace prefix declaration
            new XAttribute(XNamespace.Xmlns+"xsd", xsd.ToString()),
            //child element xsd:schema
            new XElement(xsd + "schema",
                //attribute id
                new XAttribute("id", "root"))));
Console.WriteLine(doc.ToString());

输出

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