3

我有一个为根元素设置了 namespaceURI 的 xml 文档。我想用这个 ns 添加新元素。我写了这段代码:

XmlDocument doc=new XmlDocument();
doc.LoadXml("<w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml"></w:wordDocument>");
XmlElement child=doc.CreateElement("w:body");
doc.DocumentElement.AppendChild(child);
//NamespaceURI remains empty
Assert.AreEqual(child.NamespaceURI,"http://schemas.microsoft.com/office/word/2003/wordml");

设置前缀不会影响 namespaceURI。它序列化

<w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
    <body></body>
</w:wordDocument>

代替

<w:body></w:body>

我能做些什么?谢谢你的帮助。

4

1 回答 1

4
[Test]
public void XmlSample()
{
    const string nameSpaceUri = @"http://schemas.microsoft.com/office/word/2003/wordml";
    const string prefix = "w";
    XmlDocument xmlDocument = new XmlDocument();
    XmlNode wordDocument = xmlDocument.CreateElement(prefix, "wordDocument", nameSpaceUri);
    XmlElement body = xmlDocument.CreateElement(prefix,"body",nameSpaceUri);
    xmlDocument.AppendChild(wordDocument);
    wordDocument.AppendChild(body);
    Assert.AreEqual(body.Name, "w:body");
}
于 2012-10-01T00:09:58.833 回答