Thanks for the help on the last child... Related question for situations where there is no value in the node but i need to return a "0" to maintain the appropriate output file structure. Modifying the original files slightly below:
xml
<library>
<cd>
<artist></artist>
</cd>
<book>
<title>Perl Best Practices</title>
<author>Damian Conway</author>
<isbn>0596001738</isbn>
<pages>542</pages>
<image src="http://www.oreilly.com/catalog/covers/perlbp.s.gif"
width="145" height="190" />
</book>
<book>
<title>Perl Cookbook, Second Edition</title>
<author>Tom Christiansen</author>
<author>Nathan Torkington</author>
<isbn>0596003137</isbn>
<pages>964</pages>
<image src="http://www.oreilly.com/catalog/covers/perlckbk2.s.gi
+f"
width="145" height="190" />
</book>
<book>
<title>Guitar</title>
<author>Mark Phillips</author>
<author>John Chappell</author>
<isbn>076455106X</isbn>
<pages>392</pages>
<image src="http://media.wiley.com/product_data/coverImage/6X/07
+645510/076455106X.jpg"
width="100" height="125" />
</book>
</library>
Incorporating some of the previous suggestions, new code looks like this. Problem arises when <artist> is null (or there is no entry).
#!/usr/bin/perl -w
use strict;
use warnings;
my $filename = 'library1.xml';
use XML::LibXML;
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($filename);
print $_->data . " | " foreach ($doc->findnodes('/library/cd/artis
+t/text()'));
my @nodes = $doc->findnodes('/library/book[last()]');
foreach my $node (@nodes) {
print $node->findvalue( 'title')." | \n";
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|