The easiest solution to hack quickly is to remove namespaces from your document:
require 'nokogiri' xml = Nokogiri.XML "<root xmlns='foo' xmlns:bar='whee'><a/><bar:b /></root>" p xml.xpath('//b').length
However, the above is not a valid solution if you need to save namespaces (for example, change the document and save it or you have conflicting names of elements or attributes between different namespaces). If you cannot destroy namespaces, you can either create a prefix or tell Nokogiri what matches it ...
xml = Nokogiri.XML "<root xmlns='foo' xmlns:bar='whee'><a/><bar:b /></root>" p xml.xpath('//x:a','x'=>'foo').length #=> 1
... where the string foo is the URI for the namespace of the owner element in your document, which has a default namespace (usually in the root directory), and the string x is what you want. does not conflict with another namespace already declared in your document). Or, simply put, you can simply use xmlns as the prefix for the default namespace:
p xml.xpath('//xmlns:a').length
Alternatively, if you need to leave namespaces and you can create a reasonable CSS style selector to get the nodes you need, you can use the css method:
require 'nokogiri' xml = Nokogiri.XML "<root xmlns='foo' xmlns:bar='whee'> <a/> <bar:b /> <c xmlns='jim'><d/></c> </root>" p xml.css('a').length, #=> 1 xml.css('b').length, #=> 0 xml.css('c').length, #=> 0 xml.css('d').length #=> 0
As shown above, note that this only works for nodes that are in the same namespace as the root element.
source share