如何使用Nokogiri从XML中删除元素

问题描述 投票:-1回答:2

给出此HTML:

 <products>
    <product>
      <name> product1 </name>
      <price> 21 </price>
    </product>
    <product>
      <name> product2 </name>
      <price> 0 </price>
    </product>
        <product>
      <name> product3 </name>
      <price> 10 </price>
    </product>
  </products>

我想使用Nokogiri重新创建XML文件,但是我想删除“产品价格= 0”的元素,因此它看起来像:

 <products>
    <product>
      <name> product1 </name>
      <price> 21 </price>
    </product>
    <product>
      <name> product3 </name>
      <price> 10 </price>
    </product>
  </products>

我尝试了很多事情,但似乎无济于事。

xml parsing nokogiri
2个回答
0
投票

这是更常见的Nokogiri和Ruby代码:

require 'nokogiri'

xml =<<EOT
 <products>
    <product>
      <name> product1 </name>
      <price> 21 </price>
    </product>
    <product>
      <name> product2 </name>
      <price> 0 </price>
    </product>
        <product>
      <name> product3 </name>
      <price> 10 </price>
    </product>
  </products>
EOT

doc = Nokogiri::XML(xml)

# strip the offending nodes
doc.xpath('//product/price[text()=" 0 "]/..').remove

此时,生成的XML看起来像:

doc.to_xml
# => "<?xml version=\"1.0\"?>\n" +
#    "<products>\n" +
#    "    <product>\n" +
#    "      <name> product1 </name>\n" +
#    "      <price> 21 </price>\n" +
#    "    </product>\n" +
#    "    \n" +
#    "        <product>\n" +
#    "      <name> product3 </name>\n" +
#    "      <price> 10 </price>\n" +
#    "    </product>\n" +
#    "  </products>\n"

然后简单地write

File.write('myfile.xml', doc.to_xml)

-1
投票

Nokogiri使用XPath,通过它我可以查询XML文件:

就这么简单:

require 'nokogiri'

doc = File.open("file_with_your.xml") { |f| Nokogiri::XML(f) }   // load your file with xml content

c = doc.xpath("//product[price!=0]")                             //this is the query
puts c                                                           // you can print the results
File.open("myfile.xml", "w+") do |f|                             // and create another file
  f << c
end
© www.soinside.com 2019 - 2024. All rights reserved.