2013-07-16 45 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

我認爲 「父標籤」,你的意思是根元素。你可能想documentElement方法,一拉:

#!/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

至於你提到getAttribute我假設你正在使用XML::LibXML。這裏有兩種方法獲得屬性值的示例,一種使用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"; 
相關問題