Ruby XPath 查找属性 [英] Ruby XPath to find Attribute
本文介绍了Ruby XPath 查找属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
哪些 Ruby 库可用于使用 XPath 选择属性,并将其用作其他 XPath 查询的起点.
What Ruby library can be used to select attribute using XPath, and to use it as the starting point for other XPath queries.
示例:
<root>
<add key="A" value="B" />
<add key="C" value="D" />
<add foo="E" bar="F" />
</root>
所需代码:
get_pair "//*/@key", "../@value"
get_pair "//*/@foo", "../@bar"
预期输出:
"A" "B"
"C" "D"
"E" "F"
伪实现:
def get_pair(key, value)
xml_doc.select[key].each do |a|
puts [a, a.select[value]]
end
end
推荐答案
你的出发点是 REXML
这里的挑战"是如何将属性节点视为子节点,这可以通过使用 单例方法,然后其他一切顺其自然:
The "challenge" here is how to treat an attribute node as a child node, and this can be done by using singleton methods, then everything else follows naturally:
require "rexml/document"
include REXML # so that we don't have to prefix everything with REXML::...
def get_pair(xml_doc, key, value)
XPath.each(xml_doc, key) do |node|
if node.is_a?(Attribute)
def node.parent
self.element
end
end
puts "\"#{node}\" \"#{XPath.first(node, value)}\""
end
end
xml_doc = Document.new <<EOF
<root>
<add key="A" value="B" />
<add key="C" value="D" />
<add foo="E" bar="F" />
</root>
EOF
get_pair xml_doc, "//*/@key", "../@value"
get_pair xml_doc, "//*/@foo", "../@bar"
产生:
"A" "B"
"C" "D"
"E" "F"
这篇关于Ruby XPath 查找属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文