有没有办法用ruby读取xml并轻松获取属性?可能会迭代吗?
<people>
<john id=1></john>
<Mary id=2></Mary>
</people>
我想看看玛丽或约翰斯的身份。 (约翰[ 'ID'])
答案 0 :(得分:4)
尝试this。
以上链接中的示例代码:
#!/usr/bin/ruby -w
require 'rexml/document'
include REXML
xmlfile = File.new("movies.xml")
xmldoc = Document.new(xmlfile)
# Now get the root element
root = xmldoc.root
puts "Root element : " + root.attributes["shelf"]
# This will output all the movie titles.
xmldoc.elements.each("collection/movie"){
|e| puts "Movie Title : " + e.attributes["title"]
}
答案 1 :(得分:1)
首先,您的XML格式错误:
require 'nokogiri'
doc = Nokogiri::XML(<<EOT)
<people>
<john id=1></john>
<Mary id=2></Mary>
</people>
EOT
doc.errors
# => [#<Nokogiri::XML::SyntaxError: AttValue: " or ' expected>,
# #<Nokogiri::XML::SyntaxError: attributes construct error>,
# #<Nokogiri::XML::SyntaxError: Couldn't find end of Start Tag john line 2>,
# #<Nokogiri::XML::SyntaxError: Opening and ending tag mismatch: people line 1 and john>,
# #<Nokogiri::XML::SyntaxError: Extra content at the end of the document>]
换句话说,两个标签中id
的值需要用单引号或双引号括起来。
修好后:
require 'nokogiri'
doc = Nokogiri::XML(<<EOT)
<people>
<john id="1"></john>
<Mary id="2"></Mary>
</people>
EOT
doc.at('john')['id'] # => "1"
doc.at('Mary')['id'] # => "2"
或者:
doc.search('john, Mary').map{ |n| n['id'] } # => ["1", "2"]
阅读the tutorials以获取快速启动。