我正在使用.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>
似乎属性 attr导致设置“abc:def =”“”和“xmlns:abc =”MyNamespace“” - 我想要的只是后者吗? / p>
答案 0 :(得分:1)
这是在这里工作
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.
XmlElement rootNode = xml.CreateElement("root");
rootNode.SetAttribute("xmlns:abc", "MyNamespace");
xml.AppendChild(rootNode);
XmlNode containerNode = xml.CreateElement("container", xml.DocumentElement.NamespaceURI);
rootNode.AppendChild(containerNode);
// Create the element node in question:
XmlNode elementNode = xml.CreateElement("abc", "element", "MyNamespace");
containerNode.AppendChild(elementNode);
Console.Write(rootNode.OuterXml);
,输出
<root xmlns:abc="MyNamespace"><container><abc:element /></container></root>
答案 1 :(得分:0)
您应该在顶级声明您的命名空间。
请参阅此帖子以获取示例: How do I add multiple namespaces to the root element with XmlDocument?