【问题标题】:How to write xsd:schema tag using XmlDocument如何使用 XmlDocument 编写 xsd:schema 标记
【发布时间】:2016-04-14 07:37:20
【问题描述】:

我正在尝试以编程方式编写 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>

如何让标签成为&lt;xsd:schema&gt;

已经尝试过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 中生成任何内容。

【问题讨论】:

  • XmlDocument 有一个名为 Schemas 的属性。您是否尝试过在那里添加架构定义?
  • 使用 xmlDoc.Schemas.Add(GetMySchema(xmlDoc)) 不会引发任何异常,也不会将任何 xml 写入我的目标文件。有什么好的XmlSchema使用教程你知道吗?
  • @KingKerosin 你能用 LINQ-to-XML 代替XmlDocument吗?
  • @har07 是的。请阅读以XDocument 开头的内容比XmlDocument 好得多。有什么好的教程吗?
  • @KingKerosin 我没有任何具体的教程可以推荐。以下是一些你可以学习的例子:MSDN: XDocument Class Overview, XML file creation Using XDocument in C#

标签: c# xml xsd


【解决方案1】:

使用 LINQ-to-XML,您可以将 XElements 和 XAttributess 嵌套在一定的层次结构中以构造 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>

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2010-12-08
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多