ruby - 打印顶部没有 XML 标题行的 XML 文档

标签 ruby xml nokogiri

我只是想了解如何使用 Nokogiri::XML::DocumentNokogiri::XML::DocumentFragment 来处理 to_xml

或者,我想在 Nokogiri::XML::DocumentFragment 上使用 xPath。我无法确定该怎么做,但我成功地解析了一个 Nokogiri::XML::Document

我稍后将解析和修改的 DocumentFragment 包含到另一段 XML 中,但我真的被我认为是一些非常简单的东西所困扰。

就像尝试在文档或 docfrag 上执行 to_xml,但不包括顶部的 xml 行。为什么这么难?

最佳答案

获取没有前导“PI”(processing instruction)的 Document 的 XML 的最简单方法是在根元素而不是文档上调用 to_s本身:

require 'nokogiri'
doc = Nokogiri.XML('<hello world="true" />')

puts doc
#=> <?xml version="1.0"?>
#=> <hello world="true"/>

puts doc.root
#=> <hello world="true"/>

但是,在文档或构建器级别执行此操作的“正确”方法是使用 SaveOptions :

formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT +
                    Nokogiri::XML::Node::SaveOptions::NO_DECLARATION

puts doc.to_xml( save_with:formatted_no_decl )
#=> <hello world="true"/>

# Making your code shorter, but horribly confusing for future readers
puts doc.to_xml save_with:3
#=> <hello world="true"/>


请注意 DocumentFragment 不会自动包含此 PI:

frag = Nokogiri::XML::DocumentFragment.parse('<hello world="true" />')
puts frag
#=> <hello world="true"/>

如果您在片段输出中看到 PI,则表示您在解析它时它就在那里。

xml = '<?xml version="1.0"?><hello world="true" />'
frag = Nokogiri::XML::DocumentFragment.parse(xml)
puts frag
#=> <?xml version="1.0"?><hello world="true"/>

如果是这样,并且您想摆脱任何 PI,您可以这样做应该可以通过一点 XPath 做到这一点:

frag.xpath('//processing-instruction()').remove
puts frag

…除了this does not appear to work由于oddness with XPath in DocumentFragments .要解决这些错误,请改为执行以下操作:

# To remove only PIs at the root level of the fragment
frag.xpath('processing-instruction()').remove
puts frag
#=> <hello world="true"/>

# Alternatively, to remove all PIs everywhere, including inside child nodes
frag.xpath('processing-instruction()|.//processing-instruction()').remove


如果你有一个 Builder对象,执行以下任一操作:

builder = Nokogiri::XML::Builder.new{ |xml| xml.hello(world:"true") }

puts builder.to_xml
#=> <?xml version="1.0"?>
#=> <hello world="true"/>

puts builder.doc.root.to_xml
#=> <hello world="true"/>

formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT +
                    Nokogiri::XML::Node::SaveOptions::NO_DECLARATION

puts builder.to_xml save_with:formatted_no_decl
#=> <hello world="true"/>

关于ruby - 打印顶部没有 XML 标题行的 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8218711/

相关文章:

ruby-on-rails - Thinking Sphinx 重建索引 - 高 CPU 负载

ruby - ransack 范围内的参数数量错误(给定 0,预期为 1)

ruby - 使用 mechanize/nokogiri 单击按钮(不在表单中)

ruby - 使用 Nokogiri 调整 IE 条件注释而不转换实体

ruby-on-rails - 使用绝对路径启动 Rails 服务器

ruby-on-rails - 安装 'requirements' 时 rvm 挂起

xml - 是否有 XSLT 名称元素?

javascript - 使用 jQuery 访问 XML 值

c++ - 如何使用 RapidXml 解析 XML 文件

ruby - XPath 只选择子元素(不是空白文本节点)