I hope that it has been conveyed that XML::Simple
should not be used, being superseded by far better modules a long time ago and "strongly discouraged" against by its own author, also years ago.
This example shows a way to use the parent's node in order to query siblings, as specifically asked for. (I pad your sample with the <document>
root node so to have a well-formed XML.) The answer by ikegami shows how you can more directly do what you seem to need.
If you have a reason to scan through the <title>
nodes (perhaps looking for a variety of titles), then their sibling <year>
nodes can be found by
use strict;
use warnings;
use feature 'say';
use XML::LibXML;
my $file = shift || die "Usage: $0 filename\n";
my $doc = XML::LibXML->load_xml(location => $file, no_blanks => 1);
my $xpath = '/document/movie/title';
foreach my $node ($doc->findnodes($xpath)) {
if ($node->to_literal =~ /(Titanic)/) {
say "Title: $1";
foreach my $yr ($node->parentNode->findnodes('./year')) {
say "\tyear: ", $yr->to_literal;
}
}
}
If there is always a single <year>
node under one <movie>
node then this can be simplified by the shortcut findvalue
, replacing the loop over $node->parentNode->findnodes
, for
foreach my $node ($doc->findnodes($xpath)) {
if ($node->to_literal =~ /(Titanic)/) {
say "Title: $1";
say "\tyear: ", $node->parentNode->findvalue('./year');
}
}
Here we get the text directly and so there is no need for ->to_literal
either.
There are many more methods in XML::LibXML::Node, the base class for nodes used to derive other particular classes. One of interest here may be nextSibling
, as a way to peruse other information about the title within one <movie>
.
Note that this complete and feature-full library provides many more tools for working with XML. For one, adding details to your source file, like attributes, would allow use of the library's other strengths.
The documentation is spread over a number of pages. See this post for a summary of links to relevant docs. There is also a tutorial for XML::LibXML, by the author of XML::Simple
.