【问题标题】:How can I generate XML with Nokogiri without "<?xml version=..."? [duplicate]如何在没有“<?xml version=...”的情况下使用 Nokogiri 生成 XML? [复制]
【发布时间】:2012-02-12 07:19:02
【问题描述】:

可能重复:
Print an XML document without the XML header line at the top

我对 Nokogiri::XML::Builder 有疑问。我正在使用此代码生成 XML:

builder = Nokogiri::XML::Builder.new do 
    request {
        data '1'
    }
end

结果是:

<?xml version="1.0" encoding="UTF-8"?><request><data>1</data></request>

如何删除:

<?xml version="1.0" encoding="UTF-8"?>

来自我的 XML?

【问题讨论】:

    标签: ruby xml nokogiri


    【解决方案1】:

    也许只取当前正在构建的 Document 对象的根节点——.doc——而不是整个文档?

    builder.doc.root.to_s
    

    【讨论】:

    • 它引发错误(文档已经有一个根节点)。但是 builder.parent.root.to_s 没有。谢谢。你让我做对了)
    • 应该是builder.doc.root.to_xml(或to_s)。
    【解决方案2】:

    一个快速而肮脏的答案是告诉 Nokogiri 重新解析结果输出,然后查看根:

    require 'nokogiri'
    
    builder = Nokogiri::XML::Builder.new do 
      request {
        data '1'
      }
    end
    
    puts Nokogiri::XML(builder.to_xml).root.to_xml
    

    哪些输出:

    <request>
      <data>1</data>
    </request>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      相关资源
      最近更新 更多