XmlDocument.CreateElement("prefix:child") doesn't set the NamespaceURI
.net, xml, xml-namespaces, xmldocument
Solution
[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");
}
Problem
I have a xml document with a namespaceURI set for the root element. I want to add new elements with this ns. I wrote this code: ``` 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"); ``` Setting the prefix doesn't effect the namespaceURI. And it serializes ``` <w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml"> <body></body> </w:wordDocument> ``` Instead of ``` <w:body></w:body> ``` what can i do? Thanks for your help.