panapka has asked for the wisdom of the Perl Monks concerning the following question:

use strict; use LWP::UserAgent; use HTTP::Request::Common; my $connId; # The xml_request my $xml_req = '<?xml version="1.0" encoding ="UTF-8"?><!DOCTYPE dr +l SYSTEM "http://172.XX.XXX.XXX:40500/lab/v1/api/connectionRequest.dt +d" ><drl mode="normal" connectionid="null"><openconnection username=" +admin" password="admin"/></drl>'; my $ua = LWP::UserAgent->new(); my $response = $ua->post("http://172.XX.XXX.XXX:40500/xmlApiServle +t", Content => $xml_req); if ($response->is_success) { print $response->decoded_content; $response->decoded_content =~ m/drl connectionid\=\"(.*?)\".*?\>/; $connId = $1; } else { die $response->status_line; }

The $connId contains the id but is there any way to use another Perl module and directly fetch the value instead using regular expression.if so please explain ,how? Thanks in advance. -PK

Replies are listed 'Best First'.
Re: How to fetch the value using LWP:: UserAgent
by daxim (Curate) on Jul 16, 2012 at 11:42 UTC
    You're looking for an XML parser.
    use XML::LibXML qw(); my $dom = XML::LibXML->load_xml(string => \<<'XML'); <drl connectionid="foobar" /> XML for my $node ($dom->findnodes('//drl[@connectionid]')) { print $node->getAttribute('connectionid'); }

      I tried with following code

      my $dom = XML::LibXML->load_xml(string => <<'XML'); <$response->decoded_content/> XML for my $node ($dom->findnodes('//drl[@connectionid]')) { print $node->getAttribute('connectionid');

      it is throwing the error, what is wrong here

        Your try to use here-doc there was wrong. Just pass the decoded_content as the value of "string": my $dom = XML::LibXML->load_xml(string => $response->decoded_content);
        Sorry if my advice was wrong.
Re: How to fetch the value using LWP:: UserAgent
by bulk88 (Priest) on Jul 16, 2012 at 17:00 UTC
    Yes. substr and index, do not use them in a security conscious situation since they can't understand whitespace or reordering or element trees, only where you have control over what generated the xml. Much faster than loading up a XML parser. Do a index for the 'property_name="', add the offset going right to reach the '"', then another index to the next '"', then feed the 2 numbers to substr to get whats between the quotes.
    $start = 0; $beg = index($forms, 'method=POST>', $start)+12; $end = index($forms, '</blockquote>', $beg)+14; $body = substr($forms, $beg, $end-$beg);
    This is from a php website interface, that I know the template will never change, so index will always work.