简体   繁体   English

如何使用 Nokogiri 和 Ruby 解析 XML 文件

[英]How to parse an XML file using Nokogiri and Ruby

I have a XML file:我有一个 XML 文件:

<root>
    <person name="brother">Abhijeet</person>
    <person name="sister">pratiksha</person>
</root>

I want it to parse using Nokogiri.我希望它使用 Nokogiri 进行解析。 I tried by using CSS and XPath but it returns nil or the first element value.我尝试使用 CSS 和 XPath,但它返回 nil 或第一个元素值。 How do I retrieve other values?如何检索其他值? I tried:我试过:

doc = Nokogiri::XML(xmlFile)
doc.elements.each do |f|
    f.each do |y|
         p y
    end
end

and:和:

doc.xpath("//person/sister")
doc.at_xpath("//person/sister")

This is the basic way to search for a node with a given parameter and value using CSS:这是使用 CSS 搜索具有给定参数和值的节点的基本方法:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<root>
  <person name="brother">Abhijeet</person>
  <person name="sister">pratiksha</person>
</root>
EOT

doc.at('person[name="sister"]').to_html # => "<person name=\"sister\">pratiksha</person>"

You need to research CSS and XPath and how their syntax work.您需要研究 CSS 和 XPath 以及它们的语法是如何工作的。 In XPath //person/sister means search everywhere for <sister> nodes inside <person> nodes, matching something like:在 XPath 中//person/sister意味着在<person>节点内到处搜索<sister> <person>节点,匹配如下内容:

<root>
  <person>
    <sister />
  </person>
  <person>
    <sister />
  </person>
</root>

Where it would find all the <sister /> nodes.它会在哪里找到所有<sister />节点。 It doesn't search for the parameter of a node.它不搜索节点的参数。

Don't do:不要这样做:

doc.elements.each do |f|
    f.each do |y|
         p y
    end
end

You're going to waste a lot of CPU walking through every element.您将在遍历每个元素时浪费大量 CPU。 Instead learn how selectors work, so you can take advantage of the power of libXML.而是学习选择器的工作原理,以便您可以利用 libXML 的强大功能。

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

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