使用XML :: Twig解析嵌套的椭圆文件

时间:2013-12-24 11:12:31

标签: xml perl xml-twig

我有以下OVAL定义,并希望解析它并将其存储在特定的perl对象上,如数组引用,然后将其作为对象访问

例如,访问以下xml的第一个注释attrbitue:

    <criteria operator="OR">

    <criteria operator="AND">
    <criterion test_ref="oval:org.mitre.oval:tst:123" comment="Windows XP is installed"/>
    <criterion test_ref="oval:org.mitre.oval:tst:234" comment="file foo.txt exists"/>
    </criteria>
    <criteria operator="AND" negate="true">
    <criterion test_ref="oval:org.mitre.oval:tst:345" comment="Windows 2003 is installed"/>
    <criterion test_ref="oval:org.mitre.oval:tst:456" comment="file fred.txt has a version less than 2"/>
    <criterion test_ref="oval:org.mitre.oval:tst:567" negate="true" comment=patch is installed"/>
    </criteria>
    <criterion test_ref="oval:org.mitre.oval:tst:345" comment="Windows 2003 is installed"/>
    </criteria>




it will be somthing like this:

        $arr->[0]->[1]->{oval-org-mitre-oval-tst-123}->{comment}

我尝试用XML :: Twig处理程序解析它,我得到了条件元素,但我不知道如何处理嵌套的条件元素以构建我的perl对象/数据结构

任何想法如何使用XML :: Twig和perl实现这一点?

1 个答案:

答案 0 :(得分:3)

您可以尝试使用<criteria>选择twig_handlers()元素,并使用<criterion>选择children()元素,并将属性保存在推入数组的哈希中ref变量。

#!/usr/bin/env perl

use warnings;
use strict;
use XML::Twig;

my $arr = []; 

XML::Twig->new(
    twig_handlers => {
        'criteria' => sub {
            my %hash;
            for my $child ( $_->children( 'criterion' ) ) { 
                $hash{ 
                    do { (my $k = $child->att('test_ref')) =~ tr/:./-/; $k } } = 
                        $child->att( 'comment' );
            }   
            push @$arr, { %hash };
        },  
    },  
)->parsefile(shift);

## print $arr->[0]
## or
## print $arr->[0]{'oval-org-mitre-oval-tst-123'}

使用固定的xml文件,$arr将如下:

0  ARRAY(0x25f9200)
   0  HASH(0x3613958)
      'oval-org-mitre-oval-tst-123' => 'Windows XP is installed'
      'oval-org-mitre-oval-tst-234' => 'file foo.txt exists'
   1  HASH(0x360e068)
      'oval-org-mitre-oval-tst-345' => 'Windows 2003 is installed'
      'oval-org-mitre-oval-tst-456' => 'file fred.txt has a version less than 2'
      'oval-org-mitre-oval-tst-567' => 'patch is installed'
   2  HASH(0x3613430)
      'oval-org-mitre-oval-tst-345' => 'Windows 2003 is installed'