如何使用 Ruby 删除重复的 XML 节点? [英] How can I remove duplicate XML nodes using Ruby?

查看:41
本文介绍了如何使用 Ruby 删除重复的 XML 节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的结构:

<one>
   <two>
     <three>3</three>
   </two>

   <two>
     <three>4</three>
   </two>

   <two>
     <three>3</three>
   </two>
</one>

有没有办法做到这一点:

Is there anyway of getting to this :

<one>
  <two>
    <three>3</three>
  </two>

  <two>
    <three>4</three>
  </two>

</one>

使用 Ruby 的库?我设法得到 this使用 Nokogiri.从我的测试来看,它似乎有效,但也许还有另一种方法,一种更好的方法.

using Ruby's libraries? I managed to get this using Nokogiri. From my tests, it appears to work, but maybe there's another approach, a better one.

推荐答案

用两行完成整个事情的一个怎么样?

How about one that does the whole thing in two lines?

seen = Hash.new(0)
node.traverse {|n| n.unlink if (seen[n.to_xml] += 1) > 1}

如果同一个节点可能出现在两个不同的父节点下,并且您希望它们被视为重复,您可以将第二行更改为:

If there's a possibility of the same node appearing under two different parents, and you don't want those to be considered duplicates, you can change that second line to:

node.traverse {|n| n.unlink if (seen[(n.parent.path rescue "") + n.to_xml] += 1) > 1}

这篇关于如何使用 Ruby 删除重复的 XML 节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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