使用 XmlElement 创建带有前缀的 xmlns

本文关键字:前缀 xmlns XmlElement 创建 使用 | 更新日期: 2023-09-27 18:31:03

我想创建一个具有以下结构的dom

<CreateImport xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <XmlData>
  ...other child nodes
  </XmlData>
</CreateImport>

我知道如何使用普通命名空间创建XmlElement,例如

<CreateImport xmlns="http://www.w3.org/2001/XMLSchema-instance">

但是现在我的xmlns有一个前缀i,我想以编程方式将其添加到我的XmlDocument中。我对XElementXmlElement感到困惑.前者不能有 XmlElement 型的孩子。

使用 XmlElement 创建带有前缀的 xmlns

XDocumentXElement等在 Linq To XML 中使用。但在我看来,它们也可用于以更简单的方式创建 XML 文档,就像XmlDocument一样。在您的情况下,您可以编写如下内容:

XElement root = new XElement("CreateImport", new XAttribute(XNamespace.Xmlns + "i", "http://www.w3.org/2001/XMLSchema-instance"),
                             new XElement("XmlData", 
                                          new XElement("Child1"), 
                                          new XElement("Child2")));

您可以使用root.Save("myxml.xml")将其保存到文件中。这将创建以下 XML:

<?xml version="1.0" encoding="utf-8"?>
<CreateImport xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   Content
</CreateImport>

您可以阅读 http://msdn.microsoft.com/en-US/library/bb387098.aspx 以获取更多详细信息和示例。