我正在使用 Nokogiri 读取 XML 文件。我将来自文本节点的一些信息存储在一个散列中,然后我使用它来编写一个具有不同元素排序的新 XML 文件。
但是,我想按原样保留整个原始 XML 文件 block 。我通过调用 Nokogiri 读取器对象上的“outer_xml”实例方法将它存储在一个字符串中:
reader = Nokogiri::XML::Reader(File.open(filename))
reader.each do |r|
bg = r.outer_xml if r.name=="BuyersGuide"
# store stuff in hash from rest of doc
end
我的问题是,当我使用下面的代码块编写新的 XML 文档时:
# Write the new file
builder = Nokogiri::XML::Builder.new do |xml|
#puts xml.public_methods.sort.join(", ")
#break
xml.Data {
xml.Apps {
# writing stuff from the hash
}
}
end
如何将原始 XML 内容放入我使用 Nokogiri Builder 编写的 XML 文件中?它已经明确包含元素,因此我无法调用:
xml.BuyersGuide bg
最佳答案
您可以使用公共(public)方法执行此操作(我阅读了已接受的答案,但使用私有(private)方法感到不舒服):
Nokogiri::XML::Builder.new do |xml|
xml.Data {
xml.Apps {
xml << '<foo>bar</foo>'
}
}
end.to_xml
输出:
<?xml version="1.0"?>
<Data>
<Apps>
<foo>bar</foo>
</Apps>
</Data>
关于ruby-on-rails - 我可以使用 Nokogiri 插入原始 XML 字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8152461/