简体   繁体   中英

C# clear XML innertext but not nodes

I have XML that looks like below. How can I clear all the text within the nodes without deleting any of the nodes? I want to go from my starting XML to my ending XML.

My issue is that when I do the following it clears out the nodes as well and I end up with just node1 with no children nodes:

lst = doc.selectNodes("node1");
 foreach (XmlNode node in lst)
            {
                node.InnerText = "";
            }

Starting XML:

<node1>
  <node2>
    <node4>99999</node4>
  </node2>
  <node3>abdg</node3>
</node1>

Desired ending XML:

<node1>
  <node2>
    <node4></node4>
  </node2>
  <node3></node3>
</node1>

As mentioned in the comment by Peter, by selecting "all" nodes and assigning values to it would replace all the child nodes as well.

Instead, You could query for all Leaf Nodes in the Xml and then set the value to string.Empty. For example,

var xmlDoc = XDocument.Parse(xml);
var leafNodes = xmlDoc.Descendants().Where(x=>!x.Elements().Any());

foreach(var leaf in leafNodes)
{
    leaf.SetValue(string.Empty);
}

Output

<node1>
  <node2>
    <node4></node4>
  </node2>
  <node3></node3>
</node1>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM