我想使用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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。