打印一个XML文档,顶部没有XML标题行

AKW*_*KWF 10 ruby xml nokogiri

我只是想找出如何to_xml用a Nokogiri::XML::Document或a Nokogiri::XML::DocumentFragment.

或者,我想在一个上使用xPath Nokogiri::XML::DocumentFragment.我无法确定如何做到这一点,但我成功地解析了一个Nokogiri::XML::Document.

我后来将解析并修改DocumentFragment为另一段XML,但我真的被我认为是一些非常简单的事情所困扰.

就像试图to_xml在doc或docfrag上做一样,而不是在顶部包含那个xml行.为什么这么难?

Phr*_*ogz 24

Document没有前导"PI"(处理指令)的情况下获取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"/>
Run Code Online (Sandbox Code Playgroud)

但是,在文档或构建器级别执行此操作的"正确"方法是使用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"/>
Run Code Online (Sandbox Code Playgroud)

 


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

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

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

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

如果是这样,并且你想要摆脱任何PI,你可以这样做, 应该能够用一点XPath:

frag.xpath('//processing-instruction()').remove
puts frag
Run Code Online (Sandbox Code Playgroud)

...除了因为DocumentFragments中的XPath奇怪而看起来不起作用.要解决这些错误,请执行以下操作:

# 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
Run Code Online (Sandbox Code Playgroud)

 


如果您有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"/>
Run Code Online (Sandbox Code Playgroud)