本事例展示使用XML::XPath解析xml文件.
<?xml version="1.0" encoding="utf-8" ?> <employees> <employee age="30"> <name>linux</name> <country>US</country> </employee> <employee age="10"> <name>mac</name> <country>US</country> </employee> <employee age="20"> <name>windows</name> <country>US</country> </employee> </employees>
#!/usr/bin/perl use strict; use warnings; use XML::XPath; my $xp=XML::XPath->new(filename=>"employees.xml"); #测试节点 print $xp->exists('/employees/employee[@age="10"]/name'),"\n"; #获取节点值 print $xp->findvalue('/employees/employee[@age="10"]/name'),"\n"; #获取节点属性值 print $xp->findvalue('/employees/employee[1]/@age'),"\n"; #遍历节点 my $nodeset=$xp->find('/employees/employee'); foreach my $node ($nodeset->get_nodelist){ print $node->findvalue("name"),"\n"; }