获取XML个属性值
Get XML attribute value
这是我的 XML:
<response errors="0"><person><middlename/><name>Egor</name><carsList><car default="true">0777AD</car></carsList><surname>Petrov</surname></person><funds>505.56</funds></response>
我需要获取 <car>
元素的 default
属性的值。
我在 Stack Overflow 上用 attr()
和 attributue()
找到了一些解决方案,但我没有成功使用它们。
我的代码是:
unless @account.xpath("//person//carslist").blank?
@account.xpath("//person//carslist").each do |car|
p car.attribute('default')
end
end
在我的控制台上我看到 nil 但需要看到 true。
正确的变体是:
unless @account.xpath("//person//carsList/*").blank?
@account.xpath("//person//carsList/*").each do |car|
p car.attribute('default').content
end
end
它可以是什么?
你想要:
unless @account.xpath("//person//carsList/*").blank?
注意 carsList
中的大写字母 'L' 而不是 carslist
。另请注意 /*
以获取 carList
.
的子节点
更正后的代码为:
unless @account.xpath("//person//carsList/*").blank?
@account.xpath("//person//carsList").each do |car|
p car.attribute('default')
end
end
这是我的 XML:
<response errors="0"><person><middlename/><name>Egor</name><carsList><car default="true">0777AD</car></carsList><surname>Petrov</surname></person><funds>505.56</funds></response>
我需要获取 <car>
元素的 default
属性的值。
我在 Stack Overflow 上用 attr()
和 attributue()
找到了一些解决方案,但我没有成功使用它们。
我的代码是:
unless @account.xpath("//person//carslist").blank?
@account.xpath("//person//carslist").each do |car|
p car.attribute('default')
end
end
在我的控制台上我看到 nil 但需要看到 true。
正确的变体是:
unless @account.xpath("//person//carsList/*").blank?
@account.xpath("//person//carsList/*").each do |car|
p car.attribute('default').content
end
end
它可以是什么?
你想要:
unless @account.xpath("//person//carsList/*").blank?
注意 carsList
中的大写字母 'L' 而不是 carslist
。另请注意 /*
以获取 carList
.
更正后的代码为:
unless @account.xpath("//person//carsList/*").blank?
@account.xpath("//person//carsList").each do |car|
p car.attribute('default')
end
end