jo82
jo82

Reputation: 31

Perl XML::Twig question please

Im playing around with XML::Twig library in Perl, and Im not quite sure how (or even if) I can do the following. I have no code done yet as I dont even know where to start. Im really after some ideas and I can (hopefully) go from there...

So I want to use XML::Twig to find the value "This_Is_My_Name" which is a child value of the tag "MyClass.Name". I think I can do this part, but guidance would be appreciated.

Then I want to get the "MyClass.Code" LinkValue number, which in the below example is "987654321".

Hope that makes sense. So Im not sure how to move around in such a fashion.

Please help :)

So my XML doc is as follows,

<Object Class="MyClass" Id="123456789">
    <Property Name="MyClass.Link">
        <LinkValue>
            <Id>2468</Id>
        </LinkValue>
    </Property>
    <Property Name="MyClass.Code">
        <LinkValue>
            <Id>987654321</Id>
        </LinkValue>
    </Property>
    <Property Name="MyClass.Name">
        <StringValue>This_Is_My_Name</StringValue>
    </Property>
</Object>

Upvotes: 3

Views: 2182

Answers (2)

mirod
mirod

Reputation: 16171

In this case, rather than using XPath, I usually use the tree-traversal methods. Here first_elt to find the property, then field (which is equivalent to first_child()->text) to get the link value.

#!/usr/bin/perl

use strict;
use warnings;
use XML::Twig;

my $twig = XML::Twig->new();

# parse the file
$twig->parsefile("so.xml");

# look for StringValue
my $property= $twig->first_elt( 'Property[@Name="MyClass.Code"]');
my $link= $property->field( 'LinkValue');
print $link;

Upvotes: 5

dogbane
dogbane

Reputation: 274828

You can use xpaths to extract these values. The xpath for This_Is_My_Name is /Object/Property[@Name="MyClass.Name"]/StringValue and that for LinkValue is /Object/Property[@Name="MyClass.Code"]/LinkValue/Id. The code would be:

use XML::Twig;

my $twig = XML::Twig->new();

# parse the file
$twig->parsefile("x.xml");

# look for StringValue
@nodes=$twig->findnodes('/Object/Property[@Name="MyClass.Name"]/StringValue');
$stringVal=pop(@nodes)->text();
print $stringVal."\n";

# look for LinkValue
@nodes=$twig->findnodes('/Object/Property[@Name="MyClass.Code"]/LinkValue/Id');
$linkVal=pop(@nodes)->text();
print $linkVal;

Upvotes: 9

Related Questions