基本上我想提取从节点到根的绝对路径并将其报告给控制台或文件。以下是当前的解决方案:
require "rexml/document"
include REXML
def get_path(xml_doc, key)
XPath.each(xml_doc, key) do |node|
puts "\"#{node}\""
XPath.each(node, '(ancestor::#node)') do |el|
# puts el
end
end
end
test_doc = Document.new <<EOF
<root>
<level1 key="1" value="B">
<level2 key="12" value="B" />
<level2 key="13" value="B" />
</level1>
</root>
EOF
get_path test_doc, "//*/[@key='12']"
问题是它给了我"<level2 value='B' key='12'/>"
作为输出。所需的输出是<root><level1><level2 value='B' key='12'/>
(格式可能不同,主要目标是拥有完整路径)。我只有XPath的基本知识,如果能提供任何帮助/指导,以及如何实现这一点,我将不胜感激。