【问题标题】:Nokogiri and XML Formatting When Inserting Tags插入标签时的 Nokogiri 和 XML 格式
【发布时间】:2010-10-07 21:35:28
【问题描述】:

我想使用 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>

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

【问题讨论】:

标签: ruby xml nokogiri


【解决方案1】:

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

在 XML 中,可以考虑空格 有意义的。如果你解析一个文档 包含空白节点, libxml2 将假定空格 节点是有意义的,不会 为您插入它们。

你可以告诉 libxml2 那个空格 通过传递没有意义 解析器的“noblanks”标志。到 演示一下,这里有一个例子 重现你的错误,然后做什么 你想要的:

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>

【讨论】:

  • 前几天看到你的问题时,我正在寻找一面旗帜,但在刮牦牛时分心了。为您 +1 找到答案并将其发布,并为 Nokogiri +1 摇滚。
  • 可以理解。那些牦牛(还)不刮胡子。
  • 请注意,在 Ruby 1.9 下,您可以用更简洁的方式指定单个 noblanks 标志:doc = Nokogiri::XML(xml,&amp;:noblanks)
  • &:noblanks 成功了。在第一个 build_from(doc.at('bar')).to_xml 中,产生了错误;但在第二个 build_from(doc.at('bar')).to_xml 中,输出格式正确
猜你喜欢
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多