【问题标题】:Search all child nodes of XML node for a value and remove the grandparent node在 XML 节点的所有子节点中搜索一个值并移除祖父节点
【发布时间】:2011-10-28 22:21:53
【问题描述】:

尝试使用

exportDoc.Root.Elements("string").Where(node => !(node.Element("product").HasElements) || node.Element("product").Element("type").Value != product).Remove();

删除 XML 文档中没有出现我正在搜索的 product 字符串的节点。这是我的 XML 结构的示例:

<root>
   <string id = "Hithere">
      <product>
         <type>orange</type>
         <type>yellow</type>
         <type>green</type>
      <product>
      <element2/>
      <element3/>
    </string>
    <string id ="...">
     ...
     ... 
</root>

所以我需要查看每个string 元素的product 元素和其中的每个type 元素,以查看字符串product 的值是否(输入到包含它的方法)发生。目前,如果我正在搜索的 product 字符串与第一个 type 元素的值匹配,我的代码似乎只会删除节点。

重点是从这个 xdoc 中删除所有字符串节点,这些节点没有在其 product 元素下列出我要查找的产品。

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    你需要稍微改变你的搜索条件:

    var nodesToRemove = xDoc.Root
        .Elements("string")
        .Where(node =>
            !(node.Element("product").HasElements) ||
            node.Element("product").Elements("type").All(x => x.Value != product))
        .ToList();
    

    这应该匹配 all string:product:types 与 product 值不同的元素(或者换句话说 - 如果至少有一个 &lt;type&gt; 将匹配您的 product,它将不会t 被标记为移除)。

    【讨论】:

    • 正是我想要的。谢谢!
    【解决方案2】:

    当您仍在枚举(延迟执行)时,您不能 Remove()。

    你需要更多类似的东西:

    // untested
    var toRemove = exportDoc.Root.Elements("string")
        .Where(node => !(node.Element("product").HasElements) ||
               node.Element("product").Element("type").Value != product).ToList();
    toRemove.Remove();
    

    【讨论】:

    • 感谢您的回复。我认为问题在于.Element("type") 只返回第一个type 元素。因此,如果那里只有一种产品类型,它可以工作,但如果有多种产品类型,特别是在 XML 中出现在它之前的产品类型,那么它就不会工作。
    猜你喜欢
    • 1970-01-01
    • 2011-09-18
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多