使用XML :: LibXML遍历xml节点的perl脚本 [英] perl script to iterate over xml nodes using XML::LibXML

查看:266
本文介绍了使用XML :: LibXML遍历xml节点的perl脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图提出一个perl脚本来遍历某些节点并在xml文件中获取值.

I am trying to come up with a perl script to iterate over some nodes and get values in xml file.

我的XML文件如下所示,并保存为spec.xml

My XML File looks like below and is saved spec.xml

<?xml version="1.0" encoding="UTF-8"?>
<WO xmlns="http://www.example.com/yyyy" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <WOSet>
    <SR>
     <FINISHTIME>2013-07-29T18:21:38-05:00</FINISHTIME>
     <STARTTIME xsi:nil="true" />
     <TYPE>SR</TYPE>
     <DESCRIPTION>Create CUST</DESCRIPTION>
     <EXTERNALSYSTEMID />
     <REPORTEDBY>PCAUSR</REPORTEDBY>
     <REPORTEDEMAIL />
     <STATUS>RESOLVED</STATUS>
     <SRID>1001</SRID>
     <UID>1</UID>
     <SPEC>
       <AVALUE>IT</AVALUE>
       <ATTRID>CUST_DEPT</ATTRID>
       <NALUE xsi:nil="true" />
       <TVALUE />
     </SPEC>
     <SPEC>
       <AVALUE>001</AVALUE>
       <ATTRID>DEPT_CODE</ATTRID>
       <NVALUE xsi:nil="true" />
       <TVALUE />
     </SPEC>
  </SR>
</WOSet>
  </WO> 

当我运行以下脚本时,我既未获得输出也未获得任何错误以获取有关在哪里进行修复的线索...

when I run the below script , I neither get the output nor any error to get clue on where to fix things...

我不是perl专家,希望这里的专家有所帮助...

I am not a perl expert , would love experts here to through some light...

#!/usr/bin/perl
use XML::LibXML;
use strict;
use warnings;
my $file = 'spec.xml';
my $parser = XML::LibXML->new();
my $tree = $parser->parse_file($file);
my $root = $tree->getDocumentElement;

foreach my $atrid ( $tree->findnodes('WO/WOSet/SR/SPEC') ) {
    my $name =  $atrid->findvalue('ATTRID');
    my $value =  $atrid->findvalue('AVALUE');
    print $name
    print " = ";
    print $value;
    print ";\n";
}

我的预期输出是

 CUST_DEPT = IT
DEPT_CODE = 001

推荐答案

XML在空名称空间中不包含任何名为WO的元素.您要匹配http://www.example.com/yyyy名称空间中名为WO的元素.

The XML doesn't contain any element named WO in the null namespace. You want to match the elements named WO in the http://www.example.com/yyyy namespace.

#!/usr/bin/perl

use strict;
use warnings;

use XML::LibXML               qw( );
use XML::LibXML::XPathContext qw( );

my $file = 'spec.xml';

my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($file);
my $root = $doc->getDocumentElement;

my $xpc = XML::LibXML::XPathContext->new($doc);
$xpc->registerNs(y => 'http://www.example.com/yyyy');

for my $atrid ( $xpc->findnodes('y:WO/y:WOSet/y:SR/y:SPEC') ) {
    my $name  = $xpc->findvalue('y:ATTRID', $atrid);
    my $value = $xpc->findvalue('y:AVALUE', $atrid);
    print "$name = $value\n";
}

这篇关于使用XML :: LibXML遍历xml节点的perl脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆