tags:

views:

175

answers:

2

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 $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.

+1  A: 

$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.

Anon.
Thanks, I tried this, but it didn't work, are you able to help please? my @test = $nod1->attributes(); #should return a list of attribute nodes # now get the attribure wellName from this list of attribute nodesforeach $t (@test) { print $t->getAttribute(wellName);
John
Firstly, you want to call `attributes` on the node you want to get the attributes of. Secondly, there is no `getAttribute()` method in libxml - you need to iterate over the list of attributes and call `nodeName` to find the one you want.
Anon.
+3  A: 

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";
}
Greg Bacon
+1. This is the correct way of doing it.
Anon.