如何根据其中一个子元素的值删除 XML 元素? [英] How to delete an XML element according to value of one of its children?

查看:37
本文介绍了如何根据其中一个子元素的值删除 XML 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 xml 元素:

I have an xml element looking something like this:

<Description>
    <ID>1234</ID>
    <SubDescription>
        <subID>4501</subID>
    </SubDescription>
    <SubDescription>
        <subID>4502</subID>
    </SubDescription>
</Description>

如何根据ID"子元素的值删除整个Description"元素?

How can I delete the entire "Description" element according to the value of its "ID" child?

推荐答案

您可以使用以下 xpath 选择包含值为 1234 的 ID 节点的描述节点:

You can use the following xpath to select Description nodes that contain an ID node with value 1234:

//Description[./ID[text()='1234']]

所以要删除节点,你可以这样做:

So to remove the node, you can do:

doc.xpath("//Description[./ID[text()='1234']]").remove

示例:

require 'nokogiri'

str = %q{
<root>
    <Description>
        <ID>2222</ID>
        <SubDescription>
        <subID>4501</subID>
        </SubDescription>
        <SubDescription>
        <subID>4502</subID>
        </SubDescription>
    </Description>
    <Description>
        <ID>1234</ID>
        <SubDescription>
        <subID>4501</subID>
        </SubDescription>
        <SubDescription>
        <subID>4502</subID>
        </SubDescription>
    </Description>
</root>
}
doc = Nokogiri::XML(str)
doc.xpath("//Description[./ID[text()='1234']]").remove
puts doc
#=> <root>
#=> <Description>
#=>     <ID>2222</ID>
#=>     <SubDescription>
#=>     <subID>4501</subID>
#=>     </SubDescription>
#=>     <SubDescription>
#=>     <subID>4502</subID>
#=>     </SubDescription>
#=> </Description>
#=></root>

如您所见,所需的描述节点已被删除.

As you can see, the desired description node is removed.

这篇关于如何根据其中一个子元素的值删除 XML 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆