看见了吗?你是吗?

问题描述 投票:0回答:2

尝试使用nokogiri获取属性值:

require 'nokogiri'
doc  = Nokogiri::XML("<root attr=1></root>")
doc.root.attributes

#=> {}

为什么这不起作用......?

ruby nokogiri
2个回答
1
投票

冥想:

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是你的朋友。


1
投票

XML属性值始终需要在引号中。

由于您在外部使用双引号,因此您需要在内部使用单引号:

require 'nokogiri'
doc  = Nokogiri::XML("<root attr='1'></root>")
doc.root.attributes

或者你可以反其道而行,内部有双引号,外面有单数引号。

doc  = Nokogiri::XML('<root attr="1"></root>')
© www.soinside.com 2019 - 2024. All rights reserved.