xml - Getting an attribute value using Perl XPath -
i'm trying extract attribute id messaggioutente on xml code:
<?xml version="1.0" encoding="utf-8" ?> <?meta name="generator" content="xml::smart/1.78 perl/5.022001 [mswin32]" ?> <messaggiutenti schemalocation="messagiutentischema.xsd"> <messaggioutente id="1"> <nome>prova evento</nome> <email>example@email.com</email> <sitoweb>www.example.com</sitoweb> <messaggio>sample</messaggio> </messaggioutente> </messaggiutenti> my idea use xml::xpath , xml::xpath::xmlparser in way, i'm getting incorrect result:
my $xp = xml::xpath->new(filename => 'newfile.xml'); $nodeset = $xp->find('//@id'); foreach $node ($nodeset->get_nodelist) { print xml::xpath::xmlparser::as_string($node); } the problem is, i'm trying integer value id, while code extract whole string id = "1".
what's suggestion achieve this? goal getting id number , increase until new unused id next messaggioutente value. code this, due string problem it's not correct.
$id = 1; $xp = xml::xpath->new(filename => 'newfile.xml'); $nodeset = $xp->find('//@id'); foreach $node ($nodeset->get_nodelist) { $tempvar = xml::xpath::xmlparser::as_string($node); if($node eq $id) { $id = $id + 1; } }
each element of nodeset xml::xpath::node::attribute object has getnodevalue method value of node
the best way next id in sequence find maximum value of id attributes , add 1 it
it's best use xpath expression of //messaggioutente/@id avoid picking id attribute of other element
this code demonstrates. i've addded 2 more elements sample data id values of 2 , 3 show functionality better
use strict; use warnings 'all'; use feature 'say'; use xml::xpath; use list::util 'max'; $xp = xml::xpath->new(ioref => \*data); $ids = $xp->find('//messaggioutente/@id'); $new_id = 1 + max map { $_->getnodevalue } $ids->get_nodelist; "new id = $new_id"; __data__ <?xml version="1.0" encoding="utf-8" ?> <?meta name="generator" content="xml::smart/1.78 perl/5.022001 [mswin32]" ?> <messaggiutenti schemalocation="messagiutentischema.xsd"> <messaggioutente id="1"> <nome>prova evento</nome> <email>example@email.com</email> <sitoweb>www.example.com</sitoweb> <messaggio>sample</messaggio> </messaggioutente> <messaggioutente id="2"> <nome>prova evento</nome> <email>example@email.com</email> <sitoweb>www.example.com</sitoweb> <messaggio>sample</messaggio> </messaggioutente> <messaggioutente id="3"> <nome>prova evento</nome> <email>example@email.com</email> <sitoweb>www.example.com</sitoweb> <messaggio>sample</messaggio> </messaggioutente> </messaggiutenti> output
new id = 4
Comments
Post a Comment