2012-08-27 50 views
1

我有一個xml文檔,其中爲根元素設置了namespaceURI。我想用這個ns添加新元素。我寫了這樣的代碼:XmlDocument.CreateElement(「prefix:child」)沒有設置NamespaceURI

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> 

我可以做什麼?謝謝你的幫助。

回答

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