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