感谢加勒特,我能够提出以下(丑陋的)解决方案,它肯定需要改进,但它确实有效:
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