In the case where your XPath query will find only one node (e.g.: when referring to an attribute), instead of using findnodes, you could the findvalue method to get the text content of the matching node:
#!/usr/bin/perl use strict; use warnings; use XML::LibXML; my $filename = $ARGV[0]; my $parser = XML::LibXML->new(); my $doc = $parser->parse_file($filename); my $xc = XML::LibXML::XPathContext->new( $doc->documentElement() ); foreach my $sections ($xc->findnodes('/HOSTNAME/PATROL/ACL/USERNAME')) + { my $username = $sections->findvalue('./@name'); my $permissions = $sections->findvalue('./PERMISSION'); my $host = $sections->findvalue('./HOST'); print "$username\n"; print "$permissions\n"; print "$host\n"; }
Also, if your document doesn't actually use namespaces (which your example doesn't) then you might as well leave out XML::LibXML::XPathContext and call $doc->findnodes instead.
However if your document does use namespaces then instead of doing this:
$sections->findnodes('./PERMISSION');
You need to do this for the namespace prefixes to work:
$xc->findnodes('./PERMISSION', $sections);
In reply to Re: How do you get attribute values using XML::LibXML
by grantm
in thread How do you get attribute values using XML::LibXML
by onegative
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |