使用Nokogiri将xml转换为哈希,但保留锚标记

时间:2017-09-29 02:05:16

标签: ruby-on-rails xml nokogiri

我有如下所示的xml文件。我想解析它转换为 红宝石哈希。我试着这样做:

但它剥离了锚标签,我最终了 有这样的描述。 “今天是一个”

如何将xml转换为哈希值但保留锚标记?

代码:

@doc          = File.open(xml_file) { |f| Nokogiri::XML(f) }
data          = Hash.from_xml(@doc.to_s)

XML FILE

<blah>
  <tag>
   <name>My Name</name>
   <url>www.url.com</url>
   <file>myfile.zip</file>
   <description>Today is a <a href="www.sunny.com">sunny</a></description>
 </tag>
   <tag>
   <name>Someones Name</name>
   <url>www.url2.com</url>
   <file>myfile2.zip</file>
   <description>Today is a <a href="www.rainy.com">rainy</a></description>
 </tag>
</blah>

1 个答案:

答案 0 :(得分:1)

我现在看到的唯一方法是在整个文档中转义<description>内的HTML,然后执行Hash#from_xml

doc = File.open(xml_file) { |f| Nokogiri::XML(f) }

# escape HTML inside <description>
doc.css("description").each do |node|
  node.inner_html = CGI.escapeHTML(node.inner_html)
end

data = Hash.from_xml(doc.to_s) # => 

# {"blah"=>
#   {
#     "tag"=>[
#       {
#         "name"=>"My Name", 
#         "url"=>"www.url.com", 
#         "file"=>"myfile.zip", 
#         "description"=>"Today is a <a href=\"www.sunny.com\">sunny</a>"
#       }, 
#       {
#         "name"=>"Someones Name", 
#         "url"=>"www.url2.com", 
#         "file"=>"myfile2.zip", 
#         "description"=>"Today is a <a href=\"www.rainy.com\">rainy</a>"
#       }
#     ]
#   }
# }

Nokogiri仅用于HTML转义。如果你找到另一种方法逃脱,你真的不需要它。例如:

xml = File.open(xml_file).read

# escaping inner HTML (maybe not the best way, just example)
xml.gsub!(/<description>(.*)<\/description>/, "<description>#{CGI.escapeHTML($1)}</description>")

data = Hash.from_xml(doc.to_s)