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;
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!
source
share