【发布时间】:2015-06-15 03:04:47
【问题描述】:
我正在使用 .NET 的 XmlDocument 类,因为我需要动态编辑 XML 文档。
我正在尝试创建一个如下所示的元素:
<element xmlns:abc="MyNamespace">
这是我目前编写的代码:
XmlDocument xml = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("abc", "MyNamespace");
XmlNode declarationNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(declarationNode);
// Create a root element with a default namespace.
XmlNode rootNode = xml.CreateElement("root", "rootNamespace");
xml.AppendChild(rootNode);
XmlNode containerNode = xml.CreateElement("container", xml.DocumentElement.NamespaceURI);
rootNode.AppendChild(containerNode);
// Create the element node in question:
XmlNode elementNode = xml.CreateElement("element", xml.DocumentElement.NamespaceURI);
XmlAttribute attr = xml.CreateAttribute("abc", "def", nsmgr.LookupNamespace("abc"));
elementNode.Attributes.Append(attr);
containerNode.AppendChild(elementNode);
这是我的输出:
<?xml version="1.0" encoding="UTF-8"?>
<rootNode xmlns="MyNamespace">
<container>
<element abc:def="" xmlns:abc="MyNamespace" />
</container>
</rootNode>
似乎 attribute attr 导致 "abc:def=""" 和 "xmlns:abc="MyNamespace"" 都被设置——我想要的只是后者?
【问题讨论】:
标签: .net xml xmldocument