【问题标题】:how to extract an attribute from parent tag in libxml + perl如何从libxml + perl中的父标签中提取属性
【发布时间】:2013-07-14 08:34:18
【问题描述】:

我想从父标签styling 中提取属性lang 值。我如何获得这个?

我正在使用 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>

【问题讨论】:

    标签: xml perl xml-parsing


    【解决方案1】:

    我认为“父标签”是指根元素。你可能想要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>
    

    【讨论】:

      【解决方案2】:

      正如您提到的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";
      

      【讨论】:

        【解决方案3】:
         #!/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};
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-03
          • 2015-08-12
          • 2022-01-28
          • 2012-04-03
          • 2011-10-02
          • 2021-11-24
          相关资源
          最近更新 更多