如何使用 ruby 解析 XML 作为重复标签?
How can I parse XML using ruby for a duplicate tag?
<recipes>
<recipe name="MPEG4w480f20h360AAC" mimeType="video/mp4" width="480" height="360" />
<recipe name="MP3" mimeType="audio/mpeg" />
<recipe name="j24" mimeType="image/jpeg" width="24" height="24" />
<recipe name="j64" mimeType="image/jpeg" width="64" height="64" />
<recipe name="j128" mimeType="image/jpeg" width="128" height="128" />
<recipe name="j88" mimeType="image/jpeg" height="88" />
<recipe name="j150" mimeType="image/jpeg" height="150" />
<recipe name="hqPivot" mimeType="image/jpeg" width="600" />
</recipes>
我正在编写 Ruby 脚本来验证 XML 结构。
assert(!XPath.match(xml, "recipes/recipe[@name]").empty?, "Structure of xml incorrect")
如何一一验证?
使用 Nokogiri:
require 'nokogiri'
f = File.open("test.xml")
doc = Nokogiri::XML(f)
tags = []
doc.xpath("//recipe/@name").each do |elem| # get all name of all recipes
tags << elem.value
end
p tags # show all tags
p tags == tags.uniq # are all tags unique?
f.close
此输出(使用您的样本):
["MPEG4w480f20h360AAC", "MP3", "j24", "j64", "j128", "j88", "j150", "hqPivot"]
true
<recipes>
<recipe name="MPEG4w480f20h360AAC" mimeType="video/mp4" width="480" height="360" />
<recipe name="MP3" mimeType="audio/mpeg" />
<recipe name="j24" mimeType="image/jpeg" width="24" height="24" />
<recipe name="j64" mimeType="image/jpeg" width="64" height="64" />
<recipe name="j128" mimeType="image/jpeg" width="128" height="128" />
<recipe name="j88" mimeType="image/jpeg" height="88" />
<recipe name="j150" mimeType="image/jpeg" height="150" />
<recipe name="hqPivot" mimeType="image/jpeg" width="600" />
</recipes>
我正在编写 Ruby 脚本来验证 XML 结构。
assert(!XPath.match(xml, "recipes/recipe[@name]").empty?, "Structure of xml incorrect")
如何一一验证?
使用 Nokogiri:
require 'nokogiri'
f = File.open("test.xml")
doc = Nokogiri::XML(f)
tags = []
doc.xpath("//recipe/@name").each do |elem| # get all name of all recipes
tags << elem.value
end
p tags # show all tags
p tags == tags.uniq # are all tags unique?
f.close
此输出(使用您的样本):
["MPEG4w480f20h360AAC", "MP3", "j24", "j64", "j128", "j88", "j150", "hqPivot"]
true