perl xml解析器获取xml中的xml内容

时间:2011-06-23 23:46:45

标签: xml perl

如何使用XMLParser获取item-> @url,item-> @replace和item->“value inside” 将内容作为节点的字符串,其中item-> @ cone =“one”?

<cstep>
  <item  cone="one" 
         url="http://google.com/{ccc}/cthree"
         replace="{ccc}">
            <itemsub conesub="conesub">
                    <itemsubsub  conesubsub="conesubsub" />
            </itemsub>       
  </item>
  <item  cone="two" 
         url="http://google.com/{ccc}/cthree"
         replace="{ccc}">
            <itemsub conesub="conesub">
                    <itemsubsub  conesubsub="conesubsub" />
            </itemsub>       
  </item>
</cstep>

1 个答案:

答案 0 :(得分:3)

XML::Twig

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

my $str = <<EOF;
    <cstep>
      <item  cone="one" 
             url="http://google.com/{ccc}/cthree"
             replace="{ccc}">
                <itemsub conesub="conesub">
                        <itemsubsub  conesubsub="conesubsub" />
                </itemsub>       
      </item>
      <item  cone="two" 
             url="http://google.com/{ccc}/cthree"
             replace="{ccc}">
                <itemsub conesub="conesub">
                        <itemsubsub  conesubsub="conesubsub" />
                </itemsub>       
      </item>
    </cstep>
EOF

my $t = XML::Twig->new(twig_handlers => {'cstep/item' => \&item });
$t->parse($str);

sub item {
    my ($t, $item) = @_;
    if ($item->att('cone') eq 'one') {
        print $item->att('url'    ), "\n";
        print $item->att('replace'), "\n";
    }
}

__END__

http://google.com/{ccc}/cthree
{ccc}

更新:要回答有关在子资源外指定$url的评论中的问题:

my $t = XML::Twig->new(twig_handlers => {'cstep/item' => \&item });
my $url;
$t->parse($str);
print "$url\n";

sub item {
    my ($t, $item) = @_;
    if ($item->att('cone') eq 'one') {
        $url = $item->att('url');
        print $item->att('replace'), "\n";
    }
}