使用 Nokogiri::XML::Builder 追加元素 [英] Append elements using Nokogiri::XML::Builder
本文介绍了使用 Nokogiri::XML::Builder 追加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.myRoot do |xml|
xml.oneChild
xml.anotherChild
end
end
现在我想使用构建器将一些子节点附加到 myRoot(在第二步中,我知道如何立即附加它们).我该怎么做?
我已经试过了:
node = builder.doc.xpath('//myRoot/oneChild').first
Nokogiri::XML::Builder.with(node) do |xml|
xml.childOfOneChild 'Im a child of oneChild'
end
这行不通.他们不会粘在元素上,它只是一个空的 oneChild.
Which doesn't work. They won't stick to the element, it's just an empty oneChild.
推荐答案
您的代码生成以下 XML,它似乎符合您的规范.无论如何,它不会产生一个空的oneChild
.如果这不是您想要的,您能告诉我们您的理想输出是什么吗?:
Your code produces the following XML, which seems to meet your specifications. It doesn't produce an empty oneChild
, at any rate. If this isn't what you're looking for, can you tell us what your ideal output would be?:
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>
这篇关于使用 Nokogiri::XML::Builder 追加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文