使用 Nokogiri 从空标签中递归清除 XML 文档? [英] Cleaning XML document recursively from empty tags with Nokogiri?

查看:39
本文介绍了使用 Nokogiri 从空标签中递归清除 XML 文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的 XML 文档,如下所示:

I have a nested XML document that looks like this:

<?xml version="1.0"?>
<phone>
  <name>test</name>
  <descr>description</descr>
  <empty/>
  <lines>
    <line>12345</line>
    <css/>
  </lines>
</phone>

我需要删除所有空的 XML 节点,例如 .

I need to remove all empty XML nodes, like <empty/> and <css/>.

我最终得到了类似的结果:

I ended up with something like:

doc = Nokogiri::XML::DocumentFragment.parse <<-EOXML
<phone>
  <name>test</name>
  <descr>description</descr>
  <empty/>
  <lines>
    <line>12345</line>
    <css/>
  </lines>
</phone>
EOXML

phone = doc.css("phone")
phone.children.each do | child |
    child.remove if child.inner_text == ''
end

上面的代码只删除了第一个空标签,例如<代码><空/>.我无法进入嵌套块.我想我在这里需要一些递归策略.我仔细阅读了 Nokogiri 文档并检查了很多示例,但我还没有找到解决方案.

The above code removes only the first empty tag, e.g. <empty/>. I'm not able to go inside the nested block. I think I need some recursive strategy here. I carefully read the Nokogiri documentation and checked a lot of examples but I didn't find a solution yet.

我该如何解决这个问题?

How can I fix this?

我使用的是 Ruby 1.9.3 和 Nokogiri 1.5.10.

I'm using Ruby 1.9.3 and Nokogiri 1.5.10.

推荐答案

后来者采用了不同的方法,希望能增加更多的见解.这种方法去除了烦人的额外新行,并为您提供了保留具有设置了值的属性的空字段的选项.

A latecomer with a different approach, hoping to add additional insight. This approach removes the annoying extra new lines and gives you the option to keep the empty fields that have attributes with values set.

require 'nokogiri'

doc = Nokogiri::XML::Document.parse <<-EOXML
<phone>
  <name>test</name>
  <descr>description</descr>
  <empty/>
  <lines>
    <line>12345</line>
    <css/>
  </lines>
</phone>
EOXML

def traverse_and_clean(kid)
  kid.children.map { |child| traverse_and_clean(child) }
  kid.remove if kid.content.blank?
end

traverse_and_clean(doc)

输出

<?xml version="1.0"?>
<phone>
  <name>test</name>
  <descr>description</descr>
  <lines>
    <line>12345</line>
  </lines>
</phone>

如果您发现自己处于特殊情况,需要保留一些设置了某些属性的空字段.您所要做的就是稍微更改 traverse_and_clean 方法:

If you find yourself in a peculiar case needing to keep some empty fields that have certain attributes set. All you have to do is slightly change the traverse_and_clean method:

def traverse_and_clean(kid)
  kid.children.map { |child| traverse_and_clean(child) }
  kid.remove if kid.content.blank? && kid.attributes.blank?
end

这篇关于使用 Nokogiri 从空标签中递归清除 XML 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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