如何使用 XPath 和 Ruby 获取 XML 中的绝对节点路径? [英] How to get the absolute node path in XML using XPath and Ruby?

查看:24
本文介绍了如何使用 XPath 和 Ruby 获取 XML 中的绝对节点路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想提取从节点到根的绝对路径并将其报告给控制台或文件.以下是目前的解决方案:

Basically I want to extract the absolute path from a node to root and report it to the console or a file. Below is the current solution:

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'/>" 作为输出.所需的输出是 (格式可能不同,主要目标是拥有完整路径).我只有 XPath 的基本知识,并希望得到任何帮助/指导,在哪里查看以及如何实现这个.

The issue is that it gives me "<level2 value='B' key='12'/>" as output. Desired output is <root><level1><level2 value='B' key='12'/> (format could be different, the main goal is to have a full path). I have only basic knowledge of XPath and would appreciate any help/guidance where to look and how to achieve this.

推荐答案

如果您准备使用 REXML,这里有一个 REXML 解决方案:

If you're set on REXML, here's a REXML solution:

require 'rexml/document'

test_doc = REXML::Document.new <<EOF
  <root>
    <level1 key="1" value="B">
      <level2 key="12" value="B" />
      <level2 key="13" value="B" />
    </level1>
  </root>
EOF

def get_path(xml_doc, key)
  node = REXML::XPath.first( xml_doc, key )
  path = []
  while node.parent
    path << node
    node = node.parent
  end
  path.reverse
end

path = get_path( test_doc, "//*[@key='12']" )
p path.map{ |el| el.name }.join("/")
#=> "root/level1/level2"

或者,如果您想使用其他答案中相同的 get_path 实现,您可以使用monkeypatch REXML 添加一个 ancestors 方法:

Or, if you want to use the same get_path implementation from the other answer, you can monkeypatch REXML to add an ancestors method:

class REXML::Child
  def ancestors
    ancestors = []

    # Presumably you don't want the node included in its list of ancestors
    # If you do, change the following line to    node = self
    node = self.parent

    # Presumably you want to stop at the root node, and not its owning document
    # If you want the document included in the ancestors, change the following
    # line to just    while node
    while node.parent
      ancestors << node
      node = node.parent
    end

    ancestors.reverse
  end
end

这篇关于如何使用 XPath 和 Ruby 获取 XML 中的绝对节点路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆