开发者

Different results between xpath and css queries

I'm exploring Nokogiri and have come across a perplexing issues I would appreciate someones views on. NB I'm also fairly new to Ruby so am expecting to have done something really daft. Apologies if that is the case.

I have a simple test that is comparing the results of an XPath query and a CSS query on an XML document. The CSS query works but the XPath doesn't and I'm a开发者_开发问答t a loss as to explain why.

  should "get same result from Nokogiri using XPath or CSS syntax" do

    xml_source = "<?xml version=\"1.0\" encoding=\"utf-8\"?><accounts xmlns=\"http://api.esendex.com/ns/\"><account id=\"2b4a326c-41de-4a57-a577-c7d742dc145c\" uri=\"http://api.esendex.com/v1.0/accounts/2b4a326c-41de-4a57-a577-c7d742dc145c\"><messagesremaining>100</messagesremaining></account></accounts>"

    ndoc = Nokogiri::XML(xml_source)

    node_value = ndoc.css("accounts account messagesremaining").count
    assert_equal 1, node_value

    node_value = ndoc.xpath("//accounts//account//messagesremaining").count
    assert_equal 1, node_value

  end

The second assert fails with node_value equal to zero.

Thanks in advance.


You have two issues.

First the xpath should be "//accounts/account/messagesremaining".

Second you have a default namespace "http://api...". You need to specify the namespace of each element when doing an xpath query (css queries ignore the namespace).

Sorry, i don't know Nokogiri, but I'm it has some documentation on how to used namespaces on xpath queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜