简体   繁体   English

C#清除XML内部文本,但不清除节点

[英]C# clear XML innertext but not nodes

I have XML that looks like below. 我有如下所示的XML。 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. 我想从开始的XML到结束的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: 我的问题是,当我执行以下操作时,它也清除了节点,最后得到的是只有node1且没有子节点的情况:

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

Starting XML: 启动XML:

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

Desired ending XML: 所需的结尾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. 如Peter的评论中所述,通过选择“所有”节点并为其分配值,也将替换所有子节点。

Instead, You could query for all Leaf Nodes in the Xml and then set the value to string.Empty. 相反,您可以查询Xml中的所有叶子节点,然后将值设置为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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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