如何按一定顺序打印输出?

时间:2014-12-09 17:44:40

标签: xml perl xpath

我正在尝试从XML文档中提取数据并按特定顺序打印,但我无法按此顺序打印

输入XML

<xml>
  <service>
    <title>split xml</title>
    <main>
      <doc id="001">
        <title>doc1</title>
        <delt id="0001">
          <title>delt1</title>
          <text>num1</text>
        </delt>
        <delt id="0002-A">
          <title>delt2</title>
          <text>num1</text>
        </delt>
      </doc>
      <doc id="002">
        <title>doc2</title>
        <delt id="0003">
          <title>delt3</title>
          <text>num1</text>
        </delt>
        <delt id="0004">
          <title>delt4</title>
          <text>num1</text>
        </delt>
      </doc>
    </main>
  </service>
</xml>

按此顺序输出打印

0001
delt1
0002-A
delt2
0003
delt3
0004
delt4

需要输出

delt1   0001    
delt2   0002-A
delt3   0003    
delt4   0004

这是我的代码

use File::Find;
use XML::LibXML;
use Data::Dumper;

my $path = "data.xml";
my $parser = XML::LibXML->new;
my $dom = $parser->parse_file($path) or die;

for my $sample ( $dom->findnodes('//delt/@id|//delt/title') ) {
  print $sample->textContent(),"\t";  
  print "\n";
}

2 个答案:

答案 0 :(得分:2)

这会按照你的要求行事。只需找到所有delt元素,然后提取每个元素的id属性和title子元素并打印它们。

use strict;
use warnings;

use XML::LibXML;

my $parser = XML::LibXML->new;
my $dom    = $parser->load_xml(IO => \*DATA) or die;

for my $delt ( $dom->findnodes('/xml/service/main/doc/delt') ) {
  my $id = $delt->getAttribute('id');
  my $title = $delt->findvalue('title');
  printf "%-8s%s\n", $title, $id;
}

__DATA__
<xml>
  <service>
    <title>split xml</title>
    <main>
      <doc id="001">
        <title>doc1</title>
        <delt id="0001">
          <title>delt1</title>
          <text>num1</text>
        </delt>
        <delt id="0002-A">
          <title>delt2</title>
          <text>num1</text>
        </delt>
      </doc>
      <doc id="002">
        <title>doc2</title>
        <delt id="0003">
          <title>delt3</title>
          <text>num1</text>
        </delt>
        <delt id="0004">
          <title>delt4</title>
          <text>num1</text>
        </delt>
      </doc>
    </main>
  </service>
</xml>

<强>输出

delt1   0001
delt2   0002-A
delt3   0003
delt4   0004

答案 1 :(得分:0)

use Modern::Perl;
use XML::LibXML;

my $path = "data.xml";
my $parser = XML::LibXML->new;
my $dom = $parser->parse_file($path) or die;

my %items = map { $_->textContent() } $dom->findnodes('//delt/@id|//delt/title');
print sort map { "$items{$_}\t$_\n" } keys %items;

输出:

delt1   0001
delt2   0002-A
delt3   0003
delt4   0004