Is there a way to print vertically aligned XML?

I have a configuration file that has XML in it:

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

I would like to have a pretty printer vertically align my attributes so that the file looks like this:

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

This formatting style depends on having a list of elements with the same attributes, so it probably cannot be applied in general to any XML document, but it is common to configuration files. I have read the man pages for xmllint and xmlstarlet , and I cannot find a link to such a function.

+4
source share
1 answer

I created the following script to align the columns. First I pass the xml request to xml, and then through the following:

 #!/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) 
+2
source

All Articles