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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.