gpt4 book ai didi

ruby - 将 XML 元素添加到 Nokogiri::XML::Builder 文档

转载 作者:数据小太阳 更新时间:2023-10-29 01:44:43 25 4
gpt4 key购买 nike

如何添加 Nokogiri::XML::Element使用 Nokogiri::XML::Buider 创建的 XML 文档?

我目前的解决方案是序列化元素并使用 <<让 Builder 重新解释它的方法。

orig_doc = Nokogiri::XML('<root xmlns="foobar"><a>test</a></root>')
node = orig_doc.at('/*/*[1]')

puts Nokogiri::XML::Builder.new do |doc|
doc.another {
# FIXME: this is the round-trip I would like to avoid
xml_text = node.to_xml(:skip_instruct => true).to_s
doc << xml_text

doc.second("hi")
}
end.to_xml

# The expected result is
#
# <another>
# <a xmlns="foobar">test</a>
# <second>hi</second>
# </another>

然而 Nokogiri::XML::Element是一个相当大的节点(以千字节和数千个节点为单位)并且此代码位于热路径中。分析显示序列化/解析往返非常昂贵。

如何指示 Nokogiri Builder 添加现有的 XML 元素 node在“当前”位置?

最佳答案

在不使用私有(private)方法的情况下,您可以使用 the parent method of the Builder 获取当前父元素的句柄。实例。然后您可以向其附加一个元素(甚至来自另一个文档)。例如:

require 'nokogiri'
doc1 = Nokogiri.XML('<r><a>success!</a></r>')
a = doc1.at('a')

# note that `xml` is not a Nokogiri::XML::Document,
# but rather a Nokogiri::XML::Builder instance.
doc2 = Nokogiri::XML::Builder.new do |xml|
xml.some do
xml.more do
xml.parent << a
end
end
end.doc

puts doc2
#=> <?xml version="1.0"?>
#=> <some>
#=> <more>
#=> <a>success!</a>
#=> </more>
#=> </some>

关于ruby - 将 XML 元素添加到 Nokogiri::XML::Builder 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com