2011-10-05 9 views
0

다음과 같은 형식의 엔터티가있는 큰 xml 파일을 가지고 있습니다. 누군가 xml :: twig로 어떻게 처리 할 수 ​​있습니까?xml :: twig을 사용하여 xml 파일을 구문 분석

<root > 
     <entity id="1" last_modified="2011-10-1"> 
     <entity_title> title</entity_title> 
     <entity_description>description </entity_description> 
     <entity_x> x </entity_x> 
     <entity_y> x </entity_y> 
     <entity_childs> 
      <child flag="1"> 
      <child_name>name<child_name> 
      <child_type>type1</child_type> 
      <child_x> some_text</child__x> 
      </child> 
      <child flag="1"> 
      <child_name>name1<child_name> 
      <child_type>type2</child_type> 
      <child_x> some_text</child__x> 
      </child> 
     <entity_sibling> 
      <family value="1" name="xc">fed</ext_ref> 
      <family value="1" name="df">ff</ext_ref> 
     </entity_sibling> 
    <\root> 


; 

다음 코드를 실행하여 메모리가 부족합니다!

my $file = shift ||die $!; 

my $twig = XML::Twig->new(); 

my $config = $twig->parsefile($file)->simplify(); 

print Dumper($config); 
+0

XML : : 간단하지만 파일이 너무 크고 어떤 오류 메시지 (들) 당신이 얻을 않았다 – smith

+0

interpeter 펄을 붙어 :

그래서 코드의 구조는 다음과 같이해야합니까? 시도한 코드의 관련 스 니펫을 게시하십시오. –

+1

시도한 스크립트를 게시하십시오. – Dave

답변

1

그래, XML에있는 마술이 아니다 :: 잔가지는, 당신이 $twig->parsefile($file)->simplify();를 쓰면 그 때 전체 문서를 기억에서 적재 할 것이다. 나는 당신이 원하는 비트를 얻고 나머지를 버리기 위해서 당신이 그것에 약간의 작업을해야만 할까 봐 걱정된다. 자세한 정보는 시놉시스 또는 문서의 맨 위에있는 XML :: Twig 101 섹션을보십시오.

이 글은 FAQ가되기에 앞서 모듈의 문서에 위의 설명을 추가했습니다. 당신은 단지 데이터를 추출 할 경우, 당신은 아마 entity에합니다 (twig_handlers 옵션을 사용하여) 핸들러를 설정하려면이 특정 경우, 공정 각 엔티티 다음 파일을 업데이트하는 경우 flush을 사용하여 폐기 또는 purge에서

그것에서.

#!/usr/bin/perl 
use strict; 
use warnings; 

use XML::Twig; 

my $file = shift;  

my $twig=XML::Twig->new(twig_handlers => { entity => \&process_entity },) 
        ->parsefile($file); 

exit; 

sub process_entity 
    { my($t, $entity)= @_; 

    # do what you have to do with $entity 

    $t->purge; 
    }  
4

XML :: Twig는 작거나 큰 문서의 두 가지 모드로 실행할 수 있습니다. 당신은 그것이 큽니다. 그래서 두 번째 접근법을 documentation synopsis에 나열하고 싶습니다.

큰 문서를 처리하기위한 예는 다음과 같이 진행됩니다

# at most one div will be loaded in memory 
    my $twig=XML::Twig->new( 
    twig_handlers => 
     { title => sub { $_->set_tag('h2') }, # change title tags to h2 
     para => sub { $_->set_tag('p') }, # change para to p 
     hidden => sub { $_->delete;  }, # remove hidden elements 
     list => \&my_list_process,   # process list elements 
     div  => sub { $_[0]->flush;  }, # output and free memory 
     }, 
    pretty_print => 'indented',    # output will be nicely formatted 
    empty_tags => 'html',     # outputs <empty_tag /> 
         ); 
    $twig->flush;        # flush the end of the document 

그래서 나는 당신이 그 방법뿐만 아니라 작은 문서로 기록되어 현재 사용중인 하나를 사용하려는 생각합니다.

+1

코드에서 파일을 파싱 할 수 있습니다 ... – mirod