加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:18:38 所属栏目:百科 来源:网络整理
导读:我想使用Nokogiri将节点插入 XML文档. Nokogiri使用Nokogiri :: XML :: Builder类来插入或创建新的XML. 如果我使用新方法创建XML,我可以创建漂亮的格式化XML: builder = Nokogiri::XML::Builder.new do |xml| xml.product { xml.test "hi" }endputs builder
我想使用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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读