2016-06-29 1 views
1

노드의 첫 번째 자식 노드가 모두 비어있는 XML 파일이 있으므로 XML::Twig을 사용하여 삭제하려고합니다. XML 파일은 다음과 같습니다perl의 xml 파일에있는 모든 노드의 첫 번째 자식 삭제

<stuff> 
    <a> 
     <b id=""/> 
     <b id="2"/> 
     <b id="3"/> 
     <b id="4"/> 
    </a> 
    <a> 
     <b id=""/> 
     <b id="5"/> 
    </a> 
    <a> 
     <b id=""/> 
     <b id="6"/> 
     <b id="7"/> 
     <b id="8"/> 
     <b id="9"/> 
     <b id="10"/> 
     <b id="11"/> 
    </a> 
    <a> 
     <b id=""/> 
     <b id="12"/> 
     <b id="13"/> 
     <b id="14"/> 
    </a> 
</stuff> 

그래서 내가 뭘하려고 모든 주어진 <a> 노드의 모든 첫째 <b> 아이를 삭제합니다. 내가 할 시도한 방법은 XML::Twig site on CPAN에서 유래 :

my @a = $root->children('a'); 
foreach my $delA (@a) { 
    $delA->first_child->delete(); 
} 

그러나 그것은 작동하지 않습니다. 필자는 Perl에 대한 많은 경험이 없으므로 어레이가 어떻게 구축되는지 오해하는지 궁금합니다. 누군가 내가 잘못하고있는 일과 대신해야 할 일을 지적 할 수 있습니까? 당신은 '널 IDS'와 노드를 삭제하는 것 같은

답변

2
This seems to do the trick: 

#!/usr/bin/env perl 
use strict; 
use warnings; 
use XML::Twig; 

my $twig = XML::Twig -> new (pretty_print => 'indented_a') -> parsefile('sample.xml'); 

foreach my $element ($twig -> get_xpath('./a')) { 
    $element -> first_child('b') -> delete; 
} 
$twig -> print; 

는 그러나 보인다.

그래서 방법 :

$_ -> delete for $twig -> get_xpath('./a/b[@id=""]'); 

(NB : 당신이 원하는 경우 '어디서나 구조 내에서'//a를 사용할 수)가 의미하는 것처럼,

1

귀하의 코드는 나를 위해 작동합니다.

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

my $file = 'data_sample.xml'; 
my $t = XML::Twig->new(pretty_print => 'indented'); 
$t->parsefile($file); 
my $root = $t->root; 

my @kids = $root->children('a'); 
# $_->print for @kids; 

foreach my $delA (@kids) { 
    $delA->first_child->delete(); 
} 

$_->print for @kids; 

인쇄는 first_child에서 빈 요소가 사라진 것을 알 수

<a> 
    <b id="2"/> 
    <b id="3"/> 
    <b id="4"/> 
</a> 
<a> 
    <b id="5"/> 
</a> 
<a> 
    <b id="6"/> 
    ... 
관련 문제