【问题标题】:Is there a way to pretty print XML with vertical alignment?有没有办法以垂直对齐方式漂亮地打印 XML?
【发布时间】:2011-06-16 13:52:46
【问题描述】:

我有一个配置文件,其中包含一些 XML,例如:

<Presidents>
  <President first="George" last="Washington" number="1" year="1789" />
  <President first="John" last="Adams" number="2" year="1797" />
</Presidents>

我想要一台漂亮的打印机垂直对齐我的属性,使文件看起来像:

<Presidents>
  <President first="George" last="Washington" number="1" year="1789" />
  <President first="John"   last="Adams"      number="2" year="1797" />
</Presidents>

这种格式样式依赖于具有相同属性的元素列表,因此它可能无法普遍应用于任何 xml 文档,但是,它是配置文件的常见样式。我已经阅读了 xmllintxmlstarlet 的手册页,但找不到对此类功能的任何引用。

【问题讨论】:

    标签: xml xml-formatting


    【解决方案1】:

    我创建了以下脚本来对齐列。我先通过我的xml思想xmllint,然后通过以下:

    #!/usr/bin/env ruby
    #
    # vertically aligns columns
    
    def print_buf(b)
      max_lengths={}
      max_lengths.default=0
    
      b.each do |line|
        for i in (0..line.size() - 1)
          d = line[i]
          s = d.size()
          if s > max_lengths[i] then
            max_lengths[i] = s
          end
        end
      end
    
      b.each do |line|
        for i in (0..line.size() - 1)
          print line[i], ' ' * (max_lengths[i] - line[i].size())
        end
      end
    
    end
    
    cols=0
    buf=[]
    
    ARGF.each do |line|
      columns=line.split(/( |\r\n|\n|\r)(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/m)
      if columns.size != cols then
        print_buf(buf) if !buf.empty?
        buf=[]
      end
      buf << columns
      cols = columns.size
    end
    
    print_buf(buf)
    

    【讨论】:

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