gpjahn has asked for the wisdom of the Perl Monks concerning the following question:
Hello,
I've been playing with, and trying to learn, XML::LibXML. I've been trying to get the values from specific nodes based on one of its attributes. I can get and print "all" the node values, and I can get and print just the specific attribute values, but I can't seem to figure out how to print the node values of nodes with specific attributes.
Here is the xml I'm using. I'd like to grab the values from the <Data> nodes, but only the ones with the "name" attribute that equals "NAME_2".
<xml> <Document> <Name>Places To Visit</Name> <Folder> <Place> <Name>Location 1</Name> <ExtendedName> <Data name="NAME_0">United States</Data> <Data name="NAME_1">Utah</Data> <Data name="NAME_2">Salt Lake City</Data> </ExtendedName> </Place> <Place> <Name>Location 2</Name> <ExtendedName> <Data name="NAME_0">United States</Data> <Data name="NAME_1">Rhode Island</Data> <Data name="NAME_2">Providence</Data> </ExtendedName> </Place> <Place> <Name>Location 3</Name> <ExtendedName> <Data name="NAME_0">United States</Data> <Data name="NAME_1">Wisconsin</Data> <Data name="NAME_2">Green Bay</Data> </ExtendedName> </Place> <Place> <Name>Location 4</Name> <ExtendedName> <Data name="NAME_0">United States</Data> <Data name="NAME_1">Wyoming</Data> <Data name="NAME_2">Casper</Data> </ExtendedName> </Place> </Folder> </Document> </xml>
Here is the small bit of code that I'm using to pull out the contents of the attributes, but I don't know how to get the node values. I hope that makes sense.
Thank you for your help!
#!/usr/bin/perl use strict; use warnings; use XML::LibXML; my $xml = XML::LibXML->load_xml(location => 'locations.xml'); foreach my $node2 ($xml->findnodes('//Place')) { my $attr; foreach( $node2->findnodes('./ExtendedName/Data/@name') ) { $attr = $_->textContent(); if($attr eq "NAME_2" ) { print $_->textContent() . "\n"; } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XML Node Values Based On Attributes
by choroba (Cardinal) on Sep 29, 2022 at 19:22 UTC | |
by gpjahn (Novice) on Oct 04, 2022 at 11:11 UTC | |
|
Re: XML Node Values Based On Attributes
by hippo (Archbishop) on Sep 29, 2022 at 22:13 UTC | |
by gpjahn (Novice) on Oct 04, 2022 at 11:12 UTC |