简体   繁体   English

将XML节点放入Ruby中“路径/到/节点”数组的最快/单线方法?

[英]Fastest/One-liner way to get XML nodes into array of “path/to/nodes” in Ruby?

What is the fastest, one-liner/shortest way to get an Array of "strings/that/are/paths" from an XML file, using Nokogiri preferably. 最好使用Nokogiri从XML文件中获取“字符串/那个/区域/路径”数组的最快,单线/最短的方法是什么。 I'd like to build the array with an arbitrary attribute name ('id' in this case), but also knowing how to do it for the element name would be helpful. 我想使用任意属性名称(在这种情况下为'id')构建数组,但是也知道如何为元素名称创建数组将很有帮助。

So this: 所以这:


<root id="top"> <nodeA id="almost_top"> <nodeB id="a_parent"> <nodeC id="im_a_node"/> <nodeD id="child_node"/> </nodeB> <nodeB id="child"/> </nodeA> </root>

to this: 对此:


[ "top", "top/almost_top", "top/almost_top/a_parent", "top/almost_top/a_parent/im_a_node", "top/almost_top/a_parent/child_node", "top/almost_top/child" ]

Thanks so much. 非常感谢。

Not exactly one-liner and not exactly sure how fast, but this should work: 不完全是一线,也不完全确定有多快,但这应该可以工作:

require 'nokogiri'

s = '<root id="top">
    <nodeA id="almost_top">
        <nodeB id="a_parent">
                <nodeC id="im_a_node"/>
                <nodeD id="child_node"/>
        </nodeB>
        <nodeB id="child"/>
    </nodeA>
</root>'

xml = Nokogiri::XML.parse s

def node_list elem, &proc
  return [] unless elem.class == Nokogiri::XML::Element
  str = proc.call(elem)
  [str] + elem.children.inject([]){|a,c| a+node_list(c,&proc)}.map{|e| "#{str}/#{e}"}
end

puts node_list(xml.root){|e| e['id']}.inspect
puts node_list(xml.root){|e| e.name}.inspect

which outputs: 输出:

jablan@jablan-hp:~/dev$ ruby traverse_xml.rb 
["top", "top/almost_top", "top/almost_top/a_parent", "top/almost_top/a_parent/im_a_node", "top/almost_top/a_parent/child_node", "top/almost_top/child"]
["root", "root/nodeA", "root/nodeA/nodeB", "root/nodeA/nodeB/nodeC", "root/nodeA/nodeB/nodeD", "root/nodeA/nodeB"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM