如何使用PERL脚本从XML过滤出节点 [英] How to filter out nodes from an XML using PERL script

查看:106
本文介绍了如何使用PERL脚本从XML过滤出节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题遍及整个Internet,但是我看到的所有示例都没有考虑到我明显的特殊情况.这是我的XML的摘录:

This question is all over the internet but all the examples I see do not take into account my apparently unique circumstances. Here is an excerpt from my XML:

<message type="error" from="Realtime" timestamp="Mon Nov 24 19:28:55 2014"> Could not receive from Loader </message>
<message type="warning" from="Dcd_Mux" timestamp="Mon Dec  1 02:31:18 2014"> Could not connect to Dcd </message>

我没有几个级别的节点,而是在一个消息节点上具有几个属性.我希望能够根据我的Perl脚本的参数过滤出节点.例如:如果我想过滤掉所有type ="error"的消息,并且我使用的XML仅上面有2行,那么我的输出将只是上面的警告消息.输出显示在这里:

Instead of having several levels of nodes, I just have several attributes on a message node. I want to be able to filter out nodes based on an argument to my Perl script. For example: If I wanted to filter out all messages with type="error", and I was using an XML that only had the 2 lines from above, my output would only be the warning message from above. Output shown here:

<message type="warning" from="Dcd_Mux" timestamp="Mon Dec  1 02:31:18 2014"> Could not connect to Dcd </message>

关于如何开始打开XML,遍历整个事物以及删除具有与我的过滤器匹配的属性的所有节点,我需要一些指导.我对使用LibXML做到这一点很感兴趣.

I need some direction on how to begin opening the XML, looping through the entire thing, and removing any nodes that have attributes that match my filter. I'm interested in using LibXML to get this done.

推荐答案

我使用 XML :: LibXML 作为我的XML解析器.

I use XML::LibXML as my XML parser.

use XML::LibXML qw( );

die "usage\n" if @ARGV != 2;

my ($type, $qfn) = @ARGV;
my $doc = XML::LibXML->new->parse_file($qfn);
for my $node ($doc->findnodes('//message') {
   my $type_addr = $node->getAttribute('type');
   next if !$type_addr || $type_addr ne $type;

   $node->parentNode->removeChild($node);
}

$doc->toFile($qfn);

这篇关于如何使用PERL脚本从XML过滤出节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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