XmlDocument.CreateElement(“prefix:child”)不设置NamespaceURI

时间:2012-08-27 15:53:12

标签: .net xml xml-namespaces xmldocument

我有一个xml文档,其中为根元素设置了namespaceURI。我想用这个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>

我该怎么办?谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

[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");
}