Reputation:
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?
Upvotes: 0
Views: 1775
Reputation: 1916
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();
Upvotes: 0
Reputation: 8792
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);
Upvotes: 1