在Ruby中格式化一个xml字符串

mCY*_*mCY 17 ruby xml formatting

给出一个像这样的xml字符串:

<some><nested><xml>value</xml></nested></some>
Run Code Online (Sandbox Code Playgroud)

什么是最好的选择(使用ruby)格式化它可读如下:

<some>
  <nested>
    <xml>value</xml>
  </nested>
</some>
Run Code Online (Sandbox Code Playgroud)

我在这里找到了答案:在ruby中格式化xml字符串的最佳方法是什么?,这真的很有帮助.但它格式化xml如:

<some>
  <nested>
    <xml>
      value
    </xml>
  </nested>
</some>
Run Code Online (Sandbox Code Playgroud)

因为我的xml字符串长度有点大.因此,这种格式无法读取.

提前致谢!

hal*_*elf 22

那么使用nokogiri呢?

require 'nokogiri'
source = '<some><nested><xml>value</xml></nested></some>'
doc = Nokogiri::XML source
puts doc.to_xml
# <?xml version=\"1.0\"?>\n<some>\n  <nested>\n    <xml>value</xml>\n  </nested>\n</some>\n
Run Code Online (Sandbox Code Playgroud)

  • 要删除<?xml version ="1,0"?>,只需输入`Nokogiri :: XML(source).root.to_xml` (3认同)
  • 更短的是```把Nokogiri :: XML(来源).to_xml``` (2认同)

Séb*_*nec 20

使用REXML :: Formatters :: Pretty格式化程序:

require "rexml/document" 
source = '<some><nested><xml>value</xml></nested></some>'

doc = REXML::Document.new(source)
formatter = REXML::Formatters::Pretty.new

# Compact uses as little whitespace as possible
formatter.compact = true
formatter.write(doc, $stdout)
Run Code Online (Sandbox Code Playgroud)