...">

How to print attribute value instead of element content?

I have an XML file:

     <wave waveID="1">
        <well wellID="1" wellName="A1">
          <oneDataSet>
            <rawData>0.1123975676</rawData>
          </oneDataSet>
        <well>

I am trying to print 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 name wellName, I am printing rawData values ​​(e.g. 0.1123975676). I don’t understand why, right? I tried to comment on the code in order to understand what is happening, but if the comments are incorrect, please correct me. Thank.

+3
source share
2 answers

Assuming you need an attribute wellNamefor all wellchildren of a particular wave, express it in XPath, rather than manually looping:

foreach my $n ($xc->findnodes(q<//ns:wave[@waveID='1']/ns:well/@wellName>)) {
    print $n->textContent, "\n";
}
+3
source

$node->attributes() returns a list of attribute nodes.

node XPath, XPath, .

+1

Source: https://habr.com/ru/post/1728838/


All Articles