[英]How to delete an XML element according to value of one of its children?
我有一个看起来像这样的xml元素:
<Description>
<ID>1234</ID>
<SubDescription>
<subID>4501</subID>
</SubDescription>
<SubDescription>
<subID>4502</subID>
</SubDescription>
</Description>
如何根据“ ID”子元素的值删除整个“描述”元素?
您可以使用以下xpath选择包含ID值为1234的ID节点的Description节点:
//Description[./ID[text()='1234']]
因此,要删除该节点,您可以执行以下操作:
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>
如您所见,所需的描述节点已删除。
我个人将使用@JustinKo的解决方案,尽管使用了更简单的XPath:
doc.xpath("//Description[ID='1234']").remove
但是,如果制作XPath并不是您的乐趣所在,而编写Ruby就是您的主意,那么您可以更加依赖Ruby(如果效率略低):
doc.css('ID').select{ |el| el.text=="1234" }.map(&:parent).each(&:remove)
说的是:
<ID>
的元素 "1234"
<Description>
节点(在每个节点上调用.parent
的结果) .remove
。 如果您知道只有一场比赛,可以通过以下方法简化比赛:
doc.css('ID').find{ |el| el.text=="1234" }.parent.remove
要查找ID,请执行以下操作:
id = doc.xpath("//ID").text
其中doc是通过加载xml文档创建的Nokogiri对象
要检查元素ID是否是您想要的,请尝试:
if id == "1234"
从您的xml文件中应返回true
最后删除整个Description使用:
doc.xpath("//Description").remove
您正在寻找的是:
doc = Nokogiri::XML(File.open("test.xml")) #create Nokogiri object from "test.xml"
id = doc.xpath("//ID").text #this will be a string with the id
doc.xpath("//Description").remove if id == "1234" #returns true with your xml document and remove the entire Description element."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.