有没有办法用垂直对齐来打印XML?

问题描述:

我有有一些XML像一个配置文件:有没有办法用垂直对齐来打印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认为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)