Builder忽略空节点的最干净方法是什么

Builder忽略空节点的最干净方法是什么

本文介绍了用Nokogiri :: XML :: Builder忽略空节点的最干净方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,假设我有一个类似于以下内容的构建器模板:

So let's say I have a builder template like the following:

builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
  xml.environment do |environment|
    environment.title title
    environment.feed feed
    environment.status status
    environment.description description
    # many many more
  end
end
builder.to_xml

如果 feed 描述 nil ,则可能输出:

If feed and description were nil, it could output:

<?xml version="1.0" encoding="UTF-8"?>
<environment>
  <title>title</title>
  <feed/>
  <status>status</status>
  <description/>
</environment>

我宁愿它完全忽略指甲。 实现此目标的最佳方法是什么?

I'd rather it ignored the nils altogether. What's the best way of achieving this?

所需的输出:

<?xml version="1.0" encoding="UTF-8"?>
<environment>
  <title>title</title>
  <status>status</status>
</environment>

当前解决方案:

builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
  xml.environment do |environment|
    environment.title title if title
    environment.feed feed if feed
    environment.status status if status
    environment.description description if description
    # many many more
  end
end
builder.to_xml

是否有更清洁的方法?

Is there a cleaner way?

这对Builder#initialize有用吗?

Would this be a useful option on Builder#initialize?

builder = Nokogiri :: XML :: Builder.new(:encoding =>'UTF-8',:empty_nodes => false)

推荐答案

这取决于您实际上拥有多少个字段,
,但我的建议是,您已经通过手动输入每个字段来犯错。

It depends how many fields you really have,but my suggestion is that you're already making a mistake by manually typing in each one.

如果顺序无关紧要,只需使用哈希即可。
(否则使用OrderedHash)

If order doesn't matter, just use a hash.(otherwise use an OrderedHash)

fields = {
  :title => title,
  :feed  => feed,
  :status => status,
  :description => description,
  # many more
}

builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
  xml.environment do |environment|
    fields.each do |field_name, field_value|
      if field_value
        environment.send(field_name, field_value)
      end
    end
  end
end
builder.to_xml

似乎可以正常工作。

虽然不漂亮,但至少您只需要在一个地方定义字段和值即可。
最好是对象方法吗?

It's not pretty, but at least you just have to define your fields and values in one place.Preferably an object method?

这篇关于用Nokogiri :: XML :: Builder忽略空节点的最干净方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 13:22