CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
XML attributes and values

 



Saya
Novice

Jul 14, 2003, 4:59 AM

Post #1 of 4 (442 views)
XML attributes and values Can't Post

Hi,

Is there someone who cn help me with the following:

<data>

<tuple name="Abb">ARG</tuple>

<tuple name="Reg">EU</tuple>

</data>

assuming a XML document as above with alot of data tags containing tuple tags. I want to find all tuples that have a name value equals to "Reg" and extract the tags value (eg. EU). How do I achieve that in Perl.


Jane
Novice

Jul 14, 2003, 6:10 AM

Post #2 of 4 (437 views)
Re: [Saya] XML attributes and values [In reply to] Can't Post


Code
my $str = qq(<data><tuple name="Abb">ARG</tuple><tuple name="Reg">EU</tuple></data> 
<data><tuple name="Abb">ARG</tuple><tuple name="Reg">a_neh_2-vf-4nm</tuple></data>
<data><tuple name="Abb">ARG</tuple><tuple name="Reg">a_neh_2-vf-4nm</tuple></data>
<data><tuple name="Abb">ARG</tuple><tuple name="Reg">HGYIuy 6798</tuple></data>);

# There's probably a better way but you can try these.
# Providing your values don't contain '<',

# to create an array you could...

my @vals;
$str =~ s/name="Reg">([^<]*)</push@vals,$1/eg;
print "$_\n" for @vals;

# Or to create a hash you could...

my %h;
my $name = 1;
$str =~ s/name="Reg">([^<]*)</$h{$name++}=$1/eg;
print "$h{$_}\n" foreach keys %h;




Jane.
Think |negatively :(|
map{$,--%(5>>1)^0?push@y,$_:unshift@y,$_}sort(Hacker=>another=>Perl=>Just);for(1&1=>1|0){push@y,shift@y}print"@y";


Saya
Novice

Jul 14, 2003, 6:32 AM

Post #3 of 4 (434 views)
Re: [Jane] XML attributes and values [In reply to] Can't Post

I was thinking of something like:

my $count = 0;
my $datatuple;
my $tuple;

foreach $datatuple ($doc->getElementsByTagName ('data-tuple')){
foreach $tuple ($datatuple->getElementsByTagName('tuple-field')){
$tuple->getAttributeNode('Reg');
my $test = $tuple->getNodeValue();
$count++;
print $test . "\n";
}
}

its the last bit that I am, having problems with, and that is extracting the actual value (eg. EU) into $test. Any clues ???


davorg
Thaumaturge / Moderator

Jul 15, 2003, 1:08 AM

Post #4 of 4 (432 views)
Re: [Saya] XML attributes and values [In reply to] Can't Post

That is what XPath is for. You should be using either XML::XPath or XML::LibXML.

--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives