How can I print out the attribute value instead of the element contents?
I have an XML file like this:
<wave waveID="1">
<well wellID="1" wellName="A1">
<oneDataSet>
<rawData>0.1123975676</rawData>
</oneDataSet>
<well>
I am trying to print out the wellName attribute with the following code:
my @n1 = $xc->findnodes('//ns:wave[@waveID="1"]');
# so @n1 is an array of nodes with the waveID 1
# Above you are searching from the root of the tree,
# for element wave, with attribute waveID set to 1.
foreach $开发者_StackOverflow社区nod1 (@n1) {
# $nod1 is the name of the iterator,
# which iterates through the array @n1 of node values.
my @wellNames = $nod1->getElementsByTagName('well'); #element inside the tree.
# print out the wellNames :
foreach $well_name (@wellNames) {
print $well_name->textContent;
print "\n";
}
but instead of printing out the wellName, I am printing out the rawData values (e.g. 0.1123975676). I can't see why, can you? I've tried to comment the code to help understand what is going on, but if the comments are incorrect then please correct me. Thanks.
Assuming you want the wellName
attribute of all well
children of the particular wave
, express that in XPath rather than looping by hand:
foreach my $n ($xc->findnodes(q<//ns:wave[@waveID='1']/ns:well/@wellName>)) {
print $n->textContent, "\n";
}
$node->attributes()
returns a list of Attribute nodes.
The alternative is to fetch the attribute node directly with an XPath expression, rather than using XPath to go part of the way and manually doing the rest.
精彩评论