2011-04-08 103 views
5

我有以下代码:附加元素::生成器

builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| 
    xml.myRoot do |xml| 
    xml.oneChild 
    xml.anotherChild 
    end 
end 

现在我想追加几个子节点使用生成器(在第二步myRoot,我知道如何将它们直接附加)。我怎样才能做到这一点?

我已经试过这样:

不工作。他们不会坚持这个元素,它只是一个空的oneChild。

回答

13

您的代码会生成以下XML,这似乎符合您的规范。无论如何,它不会产生空的oneChild。如果这不是你想要的,你能告诉我们你的理想输出是什么吗?:

builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| 
    xml.myRoot do |xml| 
    xml.oneChild 
    xml.anotherChild 
    end 
end 

puts builder.to_xml 

# <?xml version="1.0" encoding="UTF-8"?> 
# <myRoot> 
# <oneChild/> 
# <anotherChild/> 
# </myRoot> 

node = builder.doc.xpath('//myRoot/oneChild').first 
Nokogiri::XML::Builder.with(node) do |xml| 
    xml.childOfOneChild 'Im a child of oneChild' 
end 

puts builder.to_xml 

# <?xml version="1.0" encoding="UTF-8"?> 
# <myRoot> 
# <oneChild> 
#  <childOfOneChild>Im a child of oneChild</childOfOneChild> 
# </oneChild> 
# <anotherChild/> 
# </myRoot> 
+0

我想知道,哪里是OP?这对我很有用,非常感谢。文档:http://rdoc.info/github/tenderlove/nokogiri/master/Nokogiri/XML/Builder/.withwith – tokland 2011-05-21 11:05:41