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

I'm parsing a XML file where the data section has a number of nodes and then multiple subnodes. When I try to print out the subnodes, I get:

XML::LibXML::Element=SCALAR(0x880714) for all the details.

Here's the code, problem is in the 3rd foreach block...

#!/usr/bin/perl -w use strict; use XML::LibXML; @ARGV == 1 or die("Usage: $0 data file\n"); my $parser = XML::LibXML->new(XML_LIBXML_RECOVER => 2); $parser->recover_silently(1); my $data_file = $ARGV[0]; my $doc = $parser->parse_file( $data_file ); foreach ('root_detail_risklevel_1', 'root_detail_risklevel_2', 'root_d +etail_risklevel_3', 'root_detail_risklevel_4') { my($risk_level) = $_; print $risk_level . "\n"; foreach ($doc->findnodes("//".$_."/data")) { my($risk) = $_->findnodes('./risk'); my($check) = $_->findnodes('./checkname'); my($desc) = $_->findnodes('./description'); my($version) = $_->findnodes('./version'); my($cve) = $_->findnodes('./cve'); my($cce) = $_->findnodes('./cce'); my($summary) = $_->findnodes('./summary'); my($overview) = $_->findnodes('./overview'); my($fix) = $_->findnodes('./fix'); foreach ($_->findnodes('./details')) { my($detail) = $_->findnodes('./vulnDetail'); print $detail . "\n"; } } }

Syntax error in the innermost foreach block?

Help is much appreciated!

Scott...

Replies are listed 'Best First'.
Re: XML::LibXML help needed...
by SuicideJunkie (Vicar) on Aug 26, 2009 at 18:12 UTC

    You've got an object (of type "XML::LibXML::Element" as the print suggests).

    You are currently printing that object reference, but you want to print the contents of that node instead.

    I am not familiar with the module, but there should be a method you can call to get the contents. I imagine you will probably need to make a recursive sub to print the contents if the element contains other elements.

    $detail->toString() perhaps.

      Yes

      print $detail->to_literal

      Thanks!

Re: XML::LibXML help needed...
by ikegami (Patriarch) on Aug 26, 2009 at 18:47 UTC

    An XML::LibXML::Element object is returned. XML::LibXML::Element has XML::LibXML::Node for base class. This later has a method called toString which you should find useful.

    By the way, the first two characters of the first two characters of "./foo" are redundant. You can simply use "foo". The following are all equivalent:

    • "foo" (short for "descendant::foo")
    • "./foo" (short for "descendant::./descendant::foo")
    • "././foo" (short for "descendant::./descendant::./descendant::foo")
    • "foo/." (short for "descendant::foo/descendant::.")
    • "./foo/." (short for "descendant::./descendant::foo/descendant::.")

      Cool. Thank you!

      Scott...