在Ruby中格式化xml字符串

时间:2023-01-14 15:24:02

given an xml string like this :

给定这样的xml字符串:

<some><nested><xml>value</xml></nested></some>

what's the best option(using ruby) to format it readable like :

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

<some>
  <nested>
    <xml>value</xml>
  </nested>
</some>

I've found an answer here: what's the best way to format an xml string in ruby?, which is really helpful. But it formats xml like:

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

<some>
  <nested>
    <xml>
      value
    </xml>
  </nested>
</some>

As my xml string is a little big in length. So it is not readable in this format.

因为我的xml字符串有点长。所以这种格式是不可读的。

Thanks in advance!

提前谢谢!

2 个解决方案

#1


16  

Use the REXML::Formatters::Pretty formatter:

使用REXML::格式器::非常格式化程序:

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)

#2


16  

What about using nokogiri?

使用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

#1


16  

Use the REXML::Formatters::Pretty formatter:

使用REXML::格式器::非常格式化程序:

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)

#2


16  

What about using nokogiri?

使用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