尝试使用nokogiri获取属性值:
require 'nokogiri'
doc = Nokogiri::XML("<root attr=1></root>")
doc.root.attributes
#=> {}
为什么这不起作用......?
冥想:
require 'nokogiri'
doc = Nokogiri::XML("<root attr=1></root>")
doc.errors # => [#<Nokogiri::XML::SyntaxError: 1:12: FATAL: AttValue: " or ' expected>, #<Nokogiri::XML::SyntaxError: 1:12: FATAL: attributes construct error>, #<Nokogiri::XML::SyntaxError: 1:12: FATAL: Couldn't find end of Start Tag root line 1>, #<Nokogiri::XML::SyntaxError: 1:12: FATAL: Extra content at the end of the document>]
doc.errors
是你的朋友。
XML属性值始终需要在引号中。
由于您在外部使用双引号,因此您需要在内部使用单引号:
require 'nokogiri'
doc = Nokogiri::XML("<root attr='1'></root>")
doc.root.attributes
或者你可以反其道而行,内部有双引号,外面有单数引号。
doc = Nokogiri::XML('<root attr="1"></root>')