Search code examples
xmlperlxpathxml-libxml

parse out node and attribute XML::LibXML


I am trying to search for a value (xxxx01) of an attribute and return the node (0x100540) . Here is my xml:

  <model-response-list error="EndOfResults" throttle="86" total-models="86" xmlns="http://www.ca.com/spectrum/restful/schema/response">
   <model-responses>
      <model mh="0x100540">
         <attribute id="0x1006e">xxxx01</attribute>
      </model>
      <model mh="0x100c80">
         <attribute id="0x1006e">xxx02</attribute>
      </model>
</model-responses>
</model-response-list>

I have the xml in an var in the code below:

#Get restful req
  $client->setHost('http://wltsvpnms02.aigfpc.com:8080');
  $client->GET('/spectrum/restful/devices?attr=0x1006e', $headers) || die  "$!";
  my $parser     = XML::LibXML->new();
  my $xmldoc     = XML::LibXML->load_xml( string => $client->responseContent() )|| die "$!";

I have tried every xpath search i could find some documentation ( maybe i just cannot get my head around it) on but cannot come up with a solution.

Thanks for any help.


Solution

  • This seems to work.

    #!/usr/bin/perl
    
    use warnings;
    use strict;
    use 5.010;
    
    use XML::LibXML;
    
    my $xml = '<model-response-list error="EndOfResults" throttle="86" total-models="86" xmlns="http://www.ca.com/spectrum/restful/schema/response">
       <model-responses>
          <model mh="0x100540">
             <attribute id="0x1006e">xxxx01</attribute>
          </model>
          <model mh="0x100c80">
             <attribute id="0x1006e">xxx02</attribute>
          </model>
    </model-responses>
    </model-response-list>';
    
    my $xmldoc = XML::LibXML->load_xml( string => $xml );
    
    my @nodes = $xmldoc->findnodes(q(//*[text()='xxxx01']/../@mh));
    
    foreach (@nodes) {
      say $_->value;
    }
    

    My XPath is a bit rusty. There might be a better solution.