Never ever use Regex to handle markup languages.
La version originale de cette réponse (voir ci-dessous) utilisés XML::XPath
. Grant McLean a dit dans les commentaires:
XML::XPath
est un module ancien et unmaintained. XML::LibXML
est un module moderne, maintenu avec une API presque identique et c'est aussi plus rapide.
donc je fait une nouvelle version qui utilise XML::LibXML
(merci, Grant):
use warnings;
use strict;
use XML::LibXML;
my $doc = XML::LibXML->load_xml(location => 'articles.xml');
my $xp = XML::LibXML::XPathContext->new($doc->documentElement);
my $xpath = '/articles/article[position() < 4]';
foreach my $article ($xp->findnodes($xpath)) {
# now do something with $article
print $article.": ".$article->getName."\n";
}
Pour moi cette impression:
XML::LibXML::Element=SCALAR(0x346ef90): article
XML::LibXML::Element=SCALAR(0x346ef30): article
XML::LibXML::Element=SCALAR(0x346efa8): article
Liens vers la documentation pertinente:
La version originale de la réponse, sur la base du paquet XML::XPath
:
use warnings;
use strict;
use XML::XPath;
my $xp = XML::XPath->new(filename => 'articles.xml');
my $xpath = '/articles/article[position() < 4]';
foreach my $article ($xp->findnodes($xpath)->get_nodelist) {
# now do something with $article
print $article.": ".$article->getName ."\n";
}
qui imprime pour moi:
XML::XPath::Node::Element=REF(0x38067b8): article
XML::XPath::Node::Element=REF(0x38097e8): article
XML::XPath::Node::Element=REF(0x3809ae8): article
duplication possible de [Comment utiliser les expressions régulières Perl pour analyser des données XML?] (Http://stackoverflow.com/questions/2950661/how-can-i-use-perl-regular-expressions-to-parse -xml-data) – Quentin
@SMark: Même si. - Les expressions rationnelles Perl6 sont * toujours * le mauvais outil pour cela. ;-) – Tomalak