0

If I have an XmlNode like this

<element attribute="value">
    Content
</element>

I can get its InnerXml ("Content"), but how can I get the opposite? That is, just the outer markup separated by its opening tag and closing tags:

<element attribute="value">

and

</element>

I want to exclude the inner xml, so the OuterXml property on the XmlNode class won't do.

Do I have to build it manually by grabbing each piece and formatting them in a string? If so, besides the element's name, prefix and attributes, what other property can XML elements come with that I should remember to account for?

AxiomaticNexus
  • 6,190
  • 3
  • 41
  • 61
  • 1
    Removing all child nodes may be easier (definitely will produce more correct XML), may need to copy whole node first if you can't change document. – Alexei Levenkov Mar 03 '15 at 01:26

2 Answers2

1

So if I understand you correctly all you want is OuterXml without InnerXml. In that case you can take the outer XML and replace the content with an empty string.

var external = xml.OuterXml.Replace(xml.InnerText, string.Empty);
PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
0

You could try either of these two options if you don't mind changing the xmlnode:

foreach(XmlNode child in root.ChildNodes)
    root.RemoveChild(child);

Console.WriteLine(root.OuterXml);

Or

for (int i=0; i <root.ChildNodes.Count; i++)
  {
    root.RemoveChild(root.ChildNodes[i]);
  }

Note:

//RemoveAll did not work since it got rid of the xml attributes which you wanted to preserve
root.RemoveAll();
ziddarth
  • 1,796
  • 1
  • 14
  • 14