我从 REST API 使用了以下 XML:
<dataitems>
<dataitem colour="null">
<value>
<label>Intel</label>
<count>43</count>
</value>
<value>
<label>AMD</label>
<count>39</count>
</value>
<value>
<label>ARM</label>
<count>28</count>
</value>
</dataitem>
</dataitems>
我想在
<label>
中搜索文本标记并显示 <count>
的匹配值在一张 table 上。在 Controller 中我有:
@post_count = Nokogiri::XML(Post.item_data.to_xml)
.在 View 中,我不确定是否需要使用
@post_count.xpath
或 @post_count.search
.有人可以为我指出正确的方法和语法的正确方向吗?
提前致谢。
最佳答案
虽然我不确定您要查找哪些信息,但我有一些建议。
1) 如果您在搜索之前知道元素中的值:
doc = Nokogiri.XML(open(source_xml))
# Assuming there is only one of each label
node = doc.xpath('//label[text()="Intel"]').first
count = node.next_element.text
# or if there are many of each label
nodes = doc.xpath('//label[text()="Intel"]')
nodes.each {|node|
count = node.next_element.text
# do something with count here
}
2)假设你事先不知道标签内的名字
doc = Nokogiri.XML(open(source_xml))
labels = {}
doc.xpath('//label').each {|node|
labels[node.text] = node.next_element.text
}
# labels => {"Intel"=>"43", "AMD"=>"39", "ARM"=>"28"}
我个人更喜欢第二种解决方案,因为它为您提供了一个干净的散列,但我更喜欢尽快使用散列和数组。
关于ruby-on-rails - 如何在 XML 中查找文本并使用 Nokogiri 显示其同级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9651037/