代码之家  ›  专栏  ›  技术社区  ›  jessecurry

我可以在生成器XML输出中添加文件大小吗

  •  0
  • jessecurry  · 技术社区  · 15 年前

    我正在开发一个RubyonRails应用程序,它使用一个构建器模板生成一个大型XML文档,但我遇到了一些困难。

    XML输出必须有一个包含以字节为单位的文件大小的字段。我认为我基本上需要使用值来填充HTTP响应中的“Content-Length”头,但是更新标记的值显然会改变文件大小。

    输出应该如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
    <dataset>
      <metadata>
        <filesize>FILESIZE</filesize>
        <filename>FILENAME.xml</filename>
      </metadata>
        <data>
        .
        .
        .
        </data>
    </dataset>
    

    是否可以使用生成器模板在XML标记中添加文件大小?如果没有,是否有一些方法可以用来实现所需的结果?

    1 回复  |  直到 15 年前
        1
  •  0
  •   jessecurry    15 年前

    多亏了加勒特,我能想出以下(难看的)解决方案,它确实需要改进,但确实有效:

    class XmlMetaInjector
      require 'nokogiri'
    
      def initialize(app)  
        @app = app  
      end  
    
      def call(env)  
        status, headers, response = @app.call(env)  
        if headers['Content-Type'].include? 'application/xml'
          content_length = headers['Content-Length'].to_i # find the original content length
    
          doc = Nokogiri::XML(response.body)
          doc.xpath('/xmlns:path/xmlns:to/xmlns:node', 'xmlns' => 'http://namespace.com/').each do |node|
             # ugly method to determine content_length; if this happens more than once we're in trouble
            content_length = content_length + (content_length.to_s.length - node.content.length)
            node.content = content_length
          end
    
          # update the header to reflect the new content length
          headers['Content-Length'] = content_length.to_s
    
          [status, headers, doc.to_xml]  
        else  
          [status, headers, response]  
        end 
      end # call(env)
    end
    
    推荐文章