在Perl中解析XML文档而不知道它的结构

时间:2013-12-03 15:06:00

标签: xml perl xml-parsing

我是Perl XML模块的初学者,遗憾的是我没有找到有用的解决方案,也没有为我的问题找到手册。我想要做的是解析任何XML文件,而不知道它的结构和硬编码其标签/节点。我想得到节点的名称和值以及进一步处理的属性。

目前我只能用硬编码的节点名称解析XML,这意味着每当弹出一个新的XML文件时,我都需要一直重新编程解析器。

有人可以帮帮我吗?

谢谢。

目前我正在使用XML :: Simple和以下代码:

my $xml = new XML::Simple->XMLin( $list_file );
foreach my $xmls (@{$xml->{channel}->{item}}) {
  if (exists $xmls->{title}) { };
  if (exists $xmls->{value}) { };
  if (exists $xmls->{category}) { };
  if (exists $xmls->{description}) { };
}

2 个答案:

答案 0 :(得分:1)

任何基于树的解析器都可以。使用XML :: LibXML时,$element->childrenNodes返回元素的子元素,$element->attributes返回元素属性和xmlns声明。您可以使用$node->nodeType查看子节点的类型(元素,文本,注释等)。

答案 1 :(得分:0)

这个怎么样:

use XML::Simple;
use strict;

my $list_file = 'myfile.xml';
my $xml = XMLin($list_file);

sub identify{
  if(ref $_[0] eq 'HASH'){
    my (@nodes, @attributes);
    foreach(keys %{$_[0]}){
      if(ref $_[0]->{$_} eq 'HASH'){
        push @nodes, $_;
      }else{
        push @attributes, $_;
      }
    }
    if(@nodes){
      print "Nodes:\n";
      print "  $_\n" foreach @nodes;
    }
    if(@attributes){
      print "Attributes: Name => Value\n";
      print "  $_ => ".$_[0]->{$_}."\n" foreach @attributes;
    }
  }else{
    print 'The given element is not a node';
  }
}

identify($xml);
相关问题