根据“字符串/那个/是/路径"的数组构建XML树. (在Ruby中) [英] Building an XML tree from an Array of "strings/that/are/paths" (in Ruby)

查看:79
本文介绍了根据“字符串/那个/是/路径"的数组构建XML树. (在Ruby中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一个字符串路径数组,那么在Ruby中构建XML树的最佳方法是什么?

What is the best way to build an XML tree in Ruby if you have an Array of string paths?


paths = [
  "nodeA1",
  "nodeA1/nodeB1/nodeC1",
  "nodeA1/nodeB1/nodeC1/nodeD1/nodeE1",
  "nodeA1/nodeB1/nodeC2",
  "nodeA1/nodeB2/nodeC2",
  "nodeA3/nodeB2/nodeC3"
]
xml = 
<nodeA1>
    <nodeB1>
        <nodeC1>
            <nodeD1>
                <nodeE1/>
            </nodeD1>
        </nodeC1>
        <nodeC2/>
    </nodeB1>
    <nodeB2>
        <nodeC2/>
        <nodeC3/>
    </nodeB2>
</nodeA1>

我的第一个想法是将路径字符串拆分为一个数组,并将其深度和内容与先前的数组进行比较,但是当我进入路径"nodeA1/nodeB1/nodeC1/nodeD1/nodeE1"时,回到"nodeA1/nodeB1/nodeC2",[1]节点是共同祖先,但是至少我一直以来都这样来跟踪它是一团糟.

My first thought is to to split the path string to an array, and compare its depth and content to the previous array, but then if I get to path "nodeA1/nodeB1/nodeC1/nodeD1/nodeE1", when I go back down to "nodeA1/nodeB1/nodeC2", the [1] node is the common ancestor, but keeping track of that is messy, the way I've been doing it at least.

我也想使其递归,因此我可以在其自己的函数中处理每个嵌套级别,但是还没有任何半通用的解决方案.

I would like to make it recursive also, so I could process each nest level in its own function, but haven't come to any semi-universal solution yet.

遇到这个问题时,你们通常有什么想法或事情吗?

Any ideas or things you guys commonly do when you run into this problem?

谢谢! 兰斯

推荐答案

REXML是您的朋友!您正在获得XPath,因此请使用'em!

REXML is your friend! You're getting XPaths, so use 'em!

require 'rexml/document'

paths = [
  "nodeA1",
  "nodeA1/nodeB1/nodeC1",
  "nodeA1/nodeB1/nodeC1/nodeD1/nodeE1",
  "nodeA1/nodeB1/nodeC2",
  "nodeA1/nodeB2/nodeC2",
  "nodeA3/nodeB2/nodeC3"
]

x = REXML::Document.new
x.elements << "xml"

paths.each do |p|
  steps = p.split(/\//)
  steps.each_index do |i|
    unless REXML::XPath.first(x,"/xml/" + steps[0..i]*"/")
      REXML::XPath.first(x,"/xml/" + steps[0...i]*"/").elements << steps[i]
    end
  end
end
puts x.to_s

请注意,您的示例数据在顶层同时具有nodeA1和nodeA3,因此在这里我从一个名为"xml"的根开始.如果"3"是拼写错误,而nodeA1确实是您的根(如您的示例XML输出所示),则可以删除'x.elements<<. "xml"行并将所有"/xml/"更改为"/".

Note that your example data has both nodeA1 and nodeA3 at the top level, so I started with a root called "xml" here. If the "3" was a typo, and nodeA1 was really your root (as your sample XML output suggests), you can delete the 'x.elements << "xml"' line and change all the "/xml/"s to just "/".

这篇关于根据“字符串/那个/是/路径"的数组构建XML树. (在Ruby中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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