问题描述
我正在使用 Nokogiri::XML 来解析来自 Amazon SimpleDB 的响应.响应类似于:
I'm using Nokogiri::XML to parse responses from Amazon SimpleDB. The response is something like:
<SelectResponse xmlns="http://sdb.amazonaws.com/doc/2007-11-07/">
<SelectResult>
<Item>
<Attribute><Name>Foo</Name><Value>42</Value></Attribute>
<Attribute><Name>Bar</Name><Value>XYZ</Value></Attribute>
</Item>
</SelectResult>
</SelectResponse>
如果我直接将响应交给 Nokogiri,所有 XPath 查询(例如 doc/"//Item/Attribute[Name='Foo']/Value"
)都会返回一个空数组.但是,如果我从 SelectResponse
标记中删除 xmlns
属性,它就可以完美运行.
If I just hand the response straight over to Nokogiri, all XPath queries (e.g. doc/"//Item/Attribute[Name='Foo']/Value"
) return an empty array. But if I remove the xmlns
attribute from the SelectResponse
tag, it works perfectly.
我需要做一些额外的事情来说明命名空间声明吗?这种变通方法感觉非常像黑客.
Is there some extra thing I need to do to account for the namespace declaration? This workaround feels horribly like a hack.
推荐答案
该 XPath 查询查找不在任何命名空间中的元素.您需要告诉您的 XPath 处理器您正在 http://sdb.amazonaws.com/doc/2007-11-07/
命名空间中查找元素.
That XPath query looks for elements that are not in any namespace. You need to tell your XPath processor that you are looking for elements in the http://sdb.amazonaws.com/doc/2007-11-07/
namespace.
使用 Nokogiri 做到这一点的一种方法是:
One way to do that with Nokogiri is:
doc = Nokogiri::XML.parse(...)
doc.xpath("//aws:Item/aws:Attribute[Name='Foo']/aws:Value", {"aws" => "http://sdb.amazonaws.com/doc/2007-11-07/"})
这篇关于如何在 Nokogiri 中将 xmlns 声明与 XPath 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!