我遇到了一个问题,当我使用System.Xml类以编程方式创建XML Document然后使用Save方法时,输出XML不会对节点使用QName,而只使用本地名称。
例如期望输出
<ex:root>
<ex:something attr:name="value">
</ex:root>
但我现在得到的是
<root>
<something name="value">
</root>
这有点简化,因为我正在使用的所有命名空间都是使用文档元素上的xmlns属性完全定义的,但为了清楚起见,我省略了这些。
我知道XmlWriter类可用于保存XmlDocument,并且这需要一个XmlWriterSettings类,但我无法看到如何配置它以便我获得完整的QNames输出。
答案 0 :(得分:1)
正如您所说,根元素需要命名空间定义:
<?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方法的要求似乎是违反直觉的,因为可以认为该文档能够导出该信息,但是,嘿,这就是它的工作原理。