我已经学习了很多关于Ruby2.2和REXML的教程。这是我的xml的一个例子:
<msg user='Karim'><body action='ChkUsername' r='0'><ver v='153' /></body></msg>这就是我目前的代码:
xml = "<msg user='Karim'><body action='ChkUsername' r='0'><ver v='153' /></body></msg>"
doc = Document.new xml
puts doc.root.attributes[action]那不管用。出现了一个错误。#{classname} (NameError)的未定义局部变量或方法“action”
发布于 2015-04-14 16:03:56
你不能随机地假设变量存在。令牌action将被解释为引用(例如,变量或方法调用),因为它不是字符串或符号。你没有那个变量或方法,所以你会得到一个错误,准确地告诉你出了什么问题。
puts doc.root.attributes['action']文档的根是<msg>标记。<msg>标记没有属性action。它有一个user属性,如您所期望的那样可以访问:
> require 'rexml/document'
> xml = "<msg user='Karim'><body action='ChkUsername' r='0'><ver v='153' /></body></msg>"
> doc = REXML::Document.new(xml)
> doc.root.attributes['user']
=> "Karim"action属性进一步嵌套在文档中,在<body>元素中。
有许多方法可以询问文档(教程中都提到了这些方法),例如,
> doc.elements.each('//body') do |body|
> puts body.attributes['action']
> end
ChkUsernamehttps://stackoverflow.com/questions/29632110
复制相似问题