2013-07-16 3 views
1

부모 태그 styling에서 속성 lang 값을 추출하고 싶습니다. 이걸 어떻게 구할 수 있니?libxml + perl의 부모 태그에서 속성을 추출하는 방법

libxml을 사용하고 있습니다.

나는 getAttribute을 시도했지만 상위 태그에서는 작동하지 않습니다. 나는 "부모 태그"로 생각

<styling lang="en-US"> 
    <style id="jason" tts:color="#00FF00" /> 
    <style id="violet" tts:color="#FF0000" /> 
    <style id="sarah" tts:color="#FFCC00" /> 
    <style id="eileen" tts:color="#3333FF" /> 
</styling> 

답변

1
#!/usr/bin/perl 

# use module 
use XML::Simple; 
use Data::Dumper; 

# create object 
$xml = new XML::Simple; 

# read XML file 
$data = $xml->XMLin("data.xml"); 

$data->{styling}{lang}; 
3

, 당신은 루트 요소를 의미한다. 당신이 getAttribute을 언급 한 바와 같이 당신이 XML::LibXML를 사용하는 가정

#!/usr/bin/env perl 

use v5.12; 
use XML::LibXML 1.70; 

my $doc = 'XML::LibXML'->new(recover => 1)->parse_fh(\*DATA); 

say "GOT: ", $doc->documentElement->getAttribute('lang'); 

__DATA__ 
<styling lang="en-US"> 
    <style id="jason" tts:color="#00FF00" /> 
    <style id="violet" tts:color="#FF0000" /> 
    <style id="sarah" tts:color="#FFCC00" /> 
    <style id="eileen" tts:color="#3333FF" /> 
</styling> 
3

: 당신은 아마 documentElement 방법, 라 할 수 있습니다. 다음은 속성 값을 얻기위한 두 가지 메소드 인 XPath를 사용하는 방법과 getAttribute을 호출하는 또 다른 방법을 보여주는 샘플입니다.

#!/usr/bin/perl 

use strict; 
use XML::LibXML; 

my $xml = <<'EOF'; 
<styling lang="en-US" xmlns:tts="something"> 
    <style id="jason" tts:color="#00FF00" /> 
    <style id="violet" tts:color="#FF0000" /> 
    <style id="sarah" tts:color="#FFCC00" /> 
    <style id="eileen" tts:color="#3333FF" /> 
</styling> 
EOF 

print XML::LibXML->new->parse_string($xml)->findvalue('/styling/@lang'), "\n"; 
print XML::LibXML->new->parse_string($xml)->documentElement->getAttribute('lang'), "\n"; 
관련 문제