【问题标题】:XmlDocument.CreateElement("prefix:child") doesn't set the NamespaceURIXmlDocument.CreateElement("prefix:child") 没有设置 NamespaceURI
【发布时间】:2012-08-22 03:16:47
【问题描述】:

我有一个为根元素设置了 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>

我能做什么?感谢您的帮助。

【问题讨论】:

    标签: .net xml xml-namespaces xmldocument


    【解决方案1】:
    [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");
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多