ruby - REXML 正在换行长行。我该如何关闭它?

标签 ruby xml rexml word-wrap

我正在使用 REXML 创建 XML 文档

File.open(xmlFilename,'w') do |xmlFile|
    xmlDoc = Document.new
    # add stuff to the document...
    xmlDoc.write(xmlFile,4)
end

某些元素包含相当多的参数,因此相应的行可能会变得很长。如果它们超过 166 个字符,REXML 会插入换行符。当然,这仍然是完全有效的 XML,但我的工作流程包括一些比较和合并,如果每个元素都包含在一行中,效果最佳。

那么,有没有办法让 REXML 插入这些换行换行符?

编辑:我最终通过 tidy 推送完成的 XML 文件。作为我脚本的最后一步。如果有人知道更好的方法来做到这一点,我仍然会感激不已。

最佳答案

正如 Ryan Calhoun 在之前的回答中所说,REXML 使用 80 作为其换行长度。我很确定这是一个错误(尽管我现在找不到错误报告)。我能够通过覆盖 Formatters::Pretty 类的 write_text 方法来修复它,以便它使用可配置的 @width 属性而不是硬编码的 80。

require "rubygems"
require "rexml/document"
include REXML

long_xml = "<root><tag>As Ryan Calhoun said in his previous answer, REXML uses 80 as its wrap line length.  I'm pretty sure this is a bug (although I couldn't find a bug report just now).  I was able to *fix* it by overwriting the Formatters::Pretty class's write_text method.</tag></root>"

xml = Document.new(long_xml)

#fix bug in REXML::Formatters::Pretty
class MyPrecious < REXML::Formatters::Pretty
    def write_text( node, output )
        s = node.to_s()
        s.gsub!(/\s/,' ')
        s.squeeze!(" ")

        #The Pretty formatter code mistakenly used 80 instead of the @width variable
        #s = wrap(s, 80-@level)
        s = wrap(s, @width-@level)

        s = indent_text(s, @level, " ", true)
        output << (' '*@level + s)
    end
end

printer = MyPrecious.new(5)
printer.width = 1000
printer.compact = true
printer.write(xml, STDOUT)

关于ruby - REXML 正在换行长行。我该如何关闭它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4203180/

相关文章:

ruby - `gets.chomp.downcase!` 获取空字符串错误

ruby - RubyMotion 要求 'motion-cocoapods' 时出错

c# - 使用 XPATH 从 XML 文档中选择特定值?

java - Android 应用中的 Admob 广告问题

ruby - 从 xml 名称值转换为简单哈希

arrays - 如何从另一个数组中的多个元素中选择数组中的元素

Ruby 改变二维数组中的值

javascript - IE8 DOM 转换 XML 并从 jQuery find() 或 filter() 返回任何内容

ruby - 如何使用 XPath 和 Ruby 获取 XML 中的绝对节点路径?

ruby - REXML 格式问题