Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlDocument.CreateElement("prefix:child") doesn't set the NamespaceURI

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.

like image 260
RoadBump Avatar asked Jun 10 '26 03:06

RoadBump


1 Answers

[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");
}
like image 105
Johan Larsson Avatar answered Jun 11 '26 20:06

Johan Larsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!