XmlNode.InnerXml property - skip xmlns attribute

I have code to replace the root node with the name of an XML document, preserving its namespace.

XmlDocument doc = new XmlDocument();
Stream inStream = inmsg.BodyPart.GetOriginalDataStream();
doc.Load(inStream);

XmlNode root = doc.DocumentElement;
XmlNode replacement = doc.SelectSingleNode("/*/*[1]");

XmlNode newRoot = doc.CreateElement(replacement.Name);
XmlAttribute xmlns = (XmlAttribute)root.Attributes["xmlns"].Clone();
newRoot.Attributes.Append(xmlns);
newRoot.InnerXml = root.InnerXml; //the problem is here!

doc.ReplaceChild(newRoot, root);

With a document that starts as follows:

<OLD_ROOT xmlns="http://my.xml.namespace">
    <NEW_ROOT>

It leads to:

<NEW_ROOT xmlns="http://my.xml.namespace">
     <NEW_ROOT xmlns="http://my.xml.namespace">

The second xmlnsis that the property InnerXmlapparently sets it to the first node of its contents! What can I do to crop it without removing it later?

Unable to delete it after:

Tried the following code

XmlNode first_node = doc.SelectSingleNode("/*/*[1]");
XmlAttribute excess_xmlns = first_node.Attributes["xmlns"];
first_node.Attributes.Remove(excess_xmlns);

But this does not work, as it does not xmlnsseem to exist as an attribute for this node!

+4
source share
1 answer

Two changes:

  • xmlns newRoot doc.CreateElement. , NamespaceURI .
  • InnerXml ( xmlns), AppendChild node . .

:

XmlNode root = doc.DocumentElement;
XmlNode replacement = doc.SelectSingleNode("/*/*[1]");

XmlNode newRoot = doc.CreateElement(replacement.Name, replacement.NamespaceURI);
while (root.ChildNodes.Count > 0)
    newRoot.AppendChild(root.FirstChild);

doc.ReplaceChild(newRoot, root);
+5

Source: https://habr.com/ru/post/1543563/


All Articles