Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I am trying to get the value inside of the node "<Rule" but only if the atribute action is equal to "Required", I cant get it to work, any ideas how I could have this done using XML::XPath?
Thanks for the help!
#!/usr/bin/perl use warnings; use strict; my $a = do {local $/; <DATA>}; use XML::XPath; use XML::XPath::XMLParser; my $xp = XML::XPath->new(xml => $a); foreach my $cid ($xp->findnodes('/PartyA/com.Info')) { my $code = $cid->find('Rule/@action')->string_value; print "\n$code\n"; } __DATA__ <?xml version="1.0" encoding="UTF-8"?> <PartyA> <Real/> <com.Info> <Action>A</Action> <Rule action="Required">TQA</Rule> <Item> <Other> <Type>Key</Type> </Other> <Other> <Type>com.csc_ClientKey</Type> <OtherId>700</OtherId> </Other> <Other> <Type>Sum</Type> </Other> </Item> </com.Info> <Real/> <com.Info> <Action>A</Action> <Rule>YWX</Rule> <Item> <Other> <Type>Key</Type> </Other> <Other> <Type>com.csc_ClientKey</Type> <OtherId>500</OtherId> </Other> <Other> <Type>Sum</Type> </Other> </Item> </com.Info> </PartyA>

Replies are listed 'Best First'.
Re: Finding Data based on attribute help!
by ikegami (Patriarch) on May 17, 2010 at 15:59 UTC

    XPaths are like file system paths. If the last component of a path is a directory, it's a directory path. If the last component of a path is a file, it's a file path.

    In your case, the last component ("test") is an attribute, so you're selecting an attribute. You could select its parent

    Rule/@action="Required"/..
    but it's more typical (and flexible) to uses a subquery
    Rule[@action="Required"]

    If you're familiar with SQL, square brackets are kinda like an SQL WHERE clause.

Re: Finding Data based on attribute help!
by toolic (Bishop) on May 17, 2010 at 15:56 UTC
    This prints 'TQA':
    print $cid->find('Rule')->string_value, "\n" if $code eq 'Requ +ired';