Why doesn't Nokogiri xpath like xmlns declarations

徘徊边缘 提交于 2019-11-28 20:23:56

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 namespace http://sdb.amazonaws.com/doc/2007-11-07/

One way to do that with nokogiri is this:

doc = Nokogiri::XML.parse(...)
doc.xpath("//aws:Item/aws:Attribute[Name='Foo']/aws:Value", {"aws" => "http://sdb.amazonaws.com/doc/2007-11-07/"})
Matt Zukowski

I found this really helpful in understanding what's going on: http://tenderlovemaking.com/2009/04/23/namespaces-in-xml.html

Basically if you have a namespace defined at all (via xmlns=), you must use a namespace in your xpath searches.

So in your case, you could do one of three things:

  • Remove the xmlns attribute from the root SearchResponse. In that case your original, namespace-less xpath query will work.
  • Use the default namespace in your xpath query doc/"//xmlns:Item/xmlns:Attribute[xmlns:Name='Foo']/xmlns:Value"
  • Define a custom namespace in the second argument of the xpath method call and use that in your query, as shown in hrnt's solution above
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!