在Ruby中格式化XML字符串

22

给定这样一个 XML 字符串:

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

使用 Ruby,最佳选项是什么,以使其可读格式如下:

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

我在这里找到了一个答案:what's the best way to format an xml string in ruby?,对我非常有帮助。但它会将XML格式化为:

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

由于我的 XML 字符串长度有点长,所以在这种格式下无法阅读。

提前致谢!

2个回答

32

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

2
更短的代码是puts Nokogiri::XML(source).to_xml - banesto
3
要删除 <?xml version="1.0"?>,只需使用 Nokogiri::XML(source).root.to_xml - mCY
这个版本只是在我的XML中添加了XML节点,并将其他节点保留在一行中。REXML版本格式化了所有行。我的XML:<s:Envelope xmlns:s =“http://schemas.xmlsoap.org/soap/envelope/”> <s:Body> <SmbBureau xmlns =“http://tempuri.org/”> <bureauRequest xmlns:a =“http://schemas.datacontract.org/2004/07/SMB_WS” xmlns:i =“http://www.w3.org/2001/XMLSchema-instance”> <a:FINAL_RATING i:nil =“true”/> <a:FRAUD> N </a:FRAUD> <a:INTERNAL_OPERATION_NUMBER i:nil =“true”/> <a:STATUS> CORRECT_ANSWER </a:STATUS> </bureauRequest> </SmbBureau> </s:Body> </s:Envelope> - Foton
当再次使用doc.to_xml时,仅返回字符串格式。你们能帮我吗?我想显示属性值。 - kishore cheruku

25

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接