加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 22:49:16 所属栏目:百科 来源:网络整理
导读:我有一个配置文件,其中包含一些 XML: Presidents President first="George" last="Washington" number="1" year="1789" / President first="John" last="Adams" number="2" year="1797" //Presidents 我想有一个漂亮的打印机垂直对齐我的属性,所以文件看起
我有一个配置文件,其中包含一些 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文档,但是,它是配置文件的常见样式.我已经阅读了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(/( |rn|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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读