我遇到由此,当我创建一个XML文档以编程方式使用System.Xml类,然后使用Save方法输出XML不使用的QName的节点和只使用本地名称的问题。

例如<强>所需的输出

<ex:root>
  <ex:something attr:name="value">
</ex:root>

但我目前得到的是

<root>
  <something name="value">
</root>

此,因为我使用正在完全定义使用的xmlns文档元素的属性的所有名称空间被略微简化,但我省略,为了清楚起见在这里。

我知道,XmlWriter的类可以用来保存一个XmlDocument,而这需要一个XmlWriterSettings类,但我看不出如何配置这使得我得到充分的QName输出。

有帮助吗?

解决方案

如你说,根元素需要命名空间定义:

<?xml version="1.0"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
    xmlns:iis="http://schemas.microsoft.com/wix/IIsExtension">
    <iis:WebSite Id="asdf" />
</Wix>

对于上面的XML代码:

XmlDocument document = new XmlDocument();
document.AppendChild(document.CreateXmlDeclaration("1.0", null, null));
XmlNode rootNode = document.CreateElement("Wix", "http://schemas.microsoft.com/wix/2006/wi");
XmlAttribute attr = document.CreateAttribute("xmlns:iis", "http://www.w3.org/2000/xmlns/");
attr.Value = "http://schemas.microsoft.com/wix/IIsExtension";
rootNode.Attributes.Append(attr);
rootNode.AppendChild(document.CreateElement("iis:WebSite", "http://schemas.microsoft.com/wix/IIsExtension"));
document.AppendChild(rootNode);

通过命名空间URI作为参数传递给CreateAttribute和的createElement方法的要求似乎违反直觉的,因为它可以说,该文件能够获得这些信息的,但嘿,这就是它是如何工作的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top