计算具有特定值的节点

时间:2012-01-23 04:07:48

标签: xml perl

我有一个下面给出的格式的xml。我想在HintPath下获得Project/ItemGroup/Reference的数量。我还需要使用节点文本Private获取Project/ItemGroup/ReferenceFalse个节点的数量。如何使用Perl脚本执行此操作?

 <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <ItemGroup>
    <Reference Include="IronPython, Version= ...">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\shared\IronPython-1.1\IronPython.dll</HintPath>
     </Reference>
     <Reference Include="log4net, Version= ...">
        <SpecificVersion>False</SpecificVersion>
        <HintPath>..\binaries\log4net.dll</HintPath>
        <Private>False</Private>
     </Reference>
    </ItemGroup>
</Project>

2 个答案:

答案 0 :(得分:2)

以下是使用XML :: Twig的解决方案。任何像DOM :: LibXML这样的DOM模块也可以以非常类似的方式工作。

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $t= XML::Twig->new->parse( \*DATA);
foreach my $reference ($t->findnodes( '/Project/ItemGroup/Reference'))
  { print "HintPath count: ", $reference->children_count( 'HintPath'), "\n";
    my $private=  $reference->descendants( 'Private[text()="False"]');
    print "False Private count: $private\n";
  }

__DATA__
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <ItemGroup>
    <Reference Include="IronPython, Version= ...">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\shared\IronPython-1.1\IronPython.dll</HintPath>
     </Reference>
     <Reference Include="log4net, Version= ...">
        <SpecificVersion>False</SpecificVersion>
        <HintPath>..\binaries\log4net.dll</HintPath>
        <Private>False</Private>
     </Reference>
    </ItemGroup>
</Project>

答案 1 :(得分:1)

您可以使用XML::Simple

#!/usr/bin/perl

use XML::Simple 'XMLin';

my $xml = XMLin( join( "\n", <DATA> ), ForceArray => [ 'Reference' ] );

foreach my $reference ( @{ $xml->{ItemGroup}{Reference} } )
{
    # count the HintPath and Private (where False) elements in $reference
}

__DATA__
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
         ToolsVersion="3.5">
  <ItemGroup>
    <Reference Include="IronPython, Version= ...">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\shared\IronPython-1.1\IronPython.dll</HintPath>
    </Reference>
    <Reference Include="log4net, Version= ...">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\binaries\log4net.dll</HintPath>
      <Private>False</Private>
    </Reference>
  </ItemGroup>
</Project>