require 'nokogiri'
xml = DATA.read
xml_nokogiri = Nokogiri::XML.parse xml
widgets = xml_nokogiri.xpath("//Widget")
dates = widgets.map { |widget| widget.xpath("//DateAdded").text }
puts dates
__END__
<Widgets>
<Widget>
<Price>42</Price>
<DateAdded>04/22/1989</DateAdded>
</Widget>
<Widget>
<Price>29</Price>
<DateAdded>02/05/2015</DateAdded>
</Widget>
</Widgets>
备注:
Nokogiri::XML::NodeSet
个对象,有两个Nokogiri::XML::Element
个。其中每个都是与 Widget 标记对应的xml片段。xpath
开头的//
查询似乎是从 ROOT查询xml AGAIN 不是单个片段。xpath("DateAdded")
)答案 0 :(得分:3)
.//DateAdded
将为您提供相对的 XPath (任何嵌套的DateAdded
节点),以及没有前面斜杠的简单DateAdded
(直接子节点):
- dates = widgets.map { |widget| widget.xpath("//DateAdded").text }
# for immediate children use 'DateAdded'
+ dates = widgets.map { |widget| widget.xpath("DateAdded").text }
# for nested elements use './/DateAdded'
+ dates = widgets.map { |widget| widget.xpath(".//DateAdded").text }
#⇒ [
# [0] "04/22/1989",
# [1] "02/05/2015"
#]