[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1474
  • Last Modified:

Extract XML attribute using perl

#!/usr/bin/perl -w
use strict;
my $i;

open (IN, "a.svg") or die;
while (<IN>) {
    if (/<member name=\"(.+?)\" post=\"(.+?)\" location/) {
        $i++;
        print "$1\n";
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
a.svg
<Member name="ABC" post = "EFG" location = "QWE"></Member>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

The above perl script I had written print out the value of name & post, but what if I only want to print out the valuse of location, how do I do it???
0
xiaoxin85
Asked:
xiaoxin85
1 Solution
 
Kim RyanIT ConsultantCommented:
Just add another group, $1, $2, $3 refer to the match inside the brackets

open (IN, "a.svg") or die;
while (<IN>) {
    if (/<member name=\"(.+?)\" post=\"(.+?)\" location=\"(.+?)\" /) {
        $i++;
        print "name: $1 post: $2 location: $3\n";
    }
}
0
 
xiaoxin85Author Commented:
I want to onli get that particular attribute location because sometime the member element attribute might not be in this order. What if the "location" is the 1st attribute instead of 3rd? If is like that, then ur code do not work...
0
 
Adam314Commented:
There are modules that will handle all of the parsing of an XML file for you.   The easiest is XML::Simple.
To do what you want using that moduel:

use XML::Simple;

#Read entire file into memory
my $xml=XMLin("a.svg");

#Get location
my $location = $xml->{Member}->{location};

If that doesn't get location, what is the output from this:
use Data::Dumper;
print Dumper($xml);
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now