我有一个配置文件,其中包含一些 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>
我想有一个漂亮的打印机垂直对齐我的属性,所以文件看起来像:
<Presidents> <President first="George" last="Washington" number="1" year="1789" /> <President first="John" last="Adams" number="2" year="1797" /> </Presidents>
这种格式化样式取决于具有相同属性的元素列表,因此它可能无法一般地应用于任何xml文档,但是,它是配置文件的常见样式.我已经阅读了xmllint和xmlstarlet的手册页,我找不到任何像这样的功能的引用.
我创建了以下脚本来对齐列.我首先通过我的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)
