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

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

如果我使用新方法创建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>

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...