2015-04-01 66 views
0
<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結構。如何使用ruby解析XML以獲得重複的標記?

assert(!XPath.match(xml, "recipes/recipe[@name]").empty?, "Structure of xml incorrect") 

如何才能一一驗證?

+0

,我沒有得到你的問題? – 2015-04-01 09:39:27

+0

如何驗證下的所有[@names]? – Zaf 2015-04-01 11:14:47

+0

'//食譜/食譜[@name]'會給所有有'@name的食譜' – 2015-04-01 11:29:36

回答

0

使用引入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 
+0

非常感謝你Martin。 – Zaf 2015-04-01 11:56:17