http://qs321.pair.com?node_id=731637


in reply to XML::LibXML::XPathContext findnodes() Question

my $xpath = ’/root and /root/element1’;
How can you be at both /root and /root/element1 at the same time (and I'm not even sure that 'and' can be used even that way)? Do you mean?:
my $xpath = ’/root | /root/element1’;
Anyway, in your first case, it returns a NodeList object (which will contain no nodes), and in the second case, it returns an empty list (if there were nodes, it would return a list of Node objects)...due to the difference in the scalar vs. list context behavior of findnodes(), as implied in the post above.

Replies are listed 'Best First'.
Re^2: XML::LibXML::XPathContext findnodes() Question
by AbrahamB (Initiate) on Dec 19, 2008 at 20:54 UTC
    I'm trying to test the existence of two separate elements.
    Like /root && /root/element1. I want true if both exist, false if one exists.

    The xpath can certainly be much better, but this is a simplified example from an xml-grep program I am working on.
    I'm trying to add the functionality to test for the existence of 2 nodes separated by ' and '. I may need to use find() or findvalue() for these types of xpaths.

    Thanks for your time!
      If /root/element1 exists, then /root certainly exists.

      You should probably use $doc->findvalue instead of findnodes because your XPath expression doesn't return a nodeset but boolean value.

      warn $doc->findvalue('/root and /root/element1'), "\n"; warn $doc->findvalue('/root and /root/nosuch'), "\n";

      yields:

      true false