Print an XML document without the XML header line at the top

前端 未结 2 809
忘了有多久
忘了有多久 2020-12-06 17:30

I am just trying to find out how to to a to_xml with a Nokogiri::XML::Document or a Nokogiri::XML::DocumentFragment.

Alternati

2条回答
  •  遥遥无期
    2020-12-06 18:18

    The simplest way to get the XML for a Document without the leading "PI" (processing instruction) is to call to_s on the root element instead of the document itself:

    require 'nokogiri'
    doc = Nokogiri.XML('')
    
    puts doc
    #=> 
    #=> 
    
    puts doc.root
    #=> 
    

    The 'correct' way to do it at the document or builder level, though, is to use SaveOptions:

    formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT +
                        Nokogiri::XML::Node::SaveOptions::NO_DECLARATION
    
    puts doc.to_xml( save_with:formatted_no_decl )
    #=> 
    
    # Making your code shorter, but horribly confusing for future readers
    puts doc.to_xml save_with:3
    #=> 
    

     


    Note that DocumentFragments do not automatically include this PI:

    frag = Nokogiri::XML::DocumentFragment.parse('')
    puts frag
    #=> 
    

    If you are seeing a PI in your fragment output, it means it was there when you parsed it.

    xml = ''
    frag = Nokogiri::XML::DocumentFragment.parse(xml)
    puts frag
    #=> 
    

    If so, and you want to get rid of any PIs, you can do so should be able to do so with a little XPath:

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

    …except that this does not appear to work due to oddness with XPath in DocumentFragments. To work around these bugs do this instead:

    # To remove only PIs at the root level of the fragment
    frag.xpath('processing-instruction()').remove
    puts frag
    #=> 
    
    # Alternatively, to remove all PIs everywhere, including inside child nodes
    frag.xpath('processing-instruction()|.//processing-instruction()').remove
    

     


    If you have a Builder object, do either of:

    builder = Nokogiri::XML::Builder.new{ |xml| xml.hello(world:"true") }
    
    puts builder.to_xml
    #=> 
    #=> 
    
    puts builder.doc.root.to_xml
    #=> 
    
    formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT +
                        Nokogiri::XML::Node::SaveOptions::NO_DECLARATION
    
    puts builder.to_xml save_with:formatted_no_decl
    #=> 
    

提交回复
热议问题