ruby - 插入标签时的 Nokogiri 和 XML 格式化

标签 ruby xml nokogiri

我想使用 Nokogiri 将节点插入到 XML 文档中。 Nokogiri 使用 Nokogiri::XML::Builder 类来插入或创建新的 XML。

如果我使用 new 方法创建 XML,我能够创建漂亮的格式化 XML:

builder = Nokogiri::XML::Builder.new do |xml|
  xml.product {
    xml.test "hi"
  }
end

puts builder

输出如下:

<?xml version="1.0"?>
<product>
  <test>hi</test>
</product>       

太好了,但是我想做的是将上面的 XML 添加到现有文档,而不是创建新文档。根据 Nokogiri 文档,这可以通过使用 Builder 的 with 方法来完成,如下所示:

builder = Nokogiri::XML::Builder.with(document.at('products')) do |xml|
  xml.product {
    xml.test "hi"
  }
end

puts builder

然而,当我这样做时,XML 全部被放入一行,没有缩进。它看起来像这样:

<products><product><test>hi</test></product></products>

我是否遗漏了一些使其正确格式化的东西?

最佳答案

在 Nokogiri 邮件列表中找到了答案:

In XML, whitespace can be considered meaningful. If you parse a document that contains whitespace nodes, libxml2 will assume that whitespace nodes are meaningful and will not insert them for you.

You can tell libxml2 that whitespace is not meaningful by passing the "noblanks" flag to the parser. To demonstrate, here is an example that reproduces your error, then does what you want:

require 'nokogiri'
def build_from node
  builder = Nokogiri::XML::Builder.with(node) do|xml|
    xml.hello do
      xml.world
    end
  end
end

xml = DATA.read
doc = Nokogiri::XML(xml)
puts build_from(doc.at('bar')).to_xml
doc = Nokogiri::XML(xml) { |x| x.noblanks }
puts build_from(doc.at('bar')).to_xml

输出:

<root>
  <foo>
    <bar>
      <baz />
    </bar>
  </foo>
</root>

关于ruby - 插入标签时的 Nokogiri 和 XML 格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3886059/

相关文章:

ruby - 我如何在 Ruby 中组合 gets.chomp 和 ARGV?

ruby - Chef-solo 无法找到 Chef::Resource::PythonPip

php - Javascript 和 PHP5 中的换行符

html - 如何访问带样式的 div 内的跨度?

ruby - 将 XML 元素添加到 Nokogiri::XML::Builder 文档

ruby-on-rails - 由于 cookie,使用 authlogic 时无法在 Rails 中创建用户

ruby - Rally Ruby API - 向 'description' 字段添加换行符

javascript - 基本 "Raw"Ajax 调用

java - 如何更改 IntelliJ IDEA 中的 XML 缩进?

ruby - Nokogiri:倾斜访问名为 name 的节点