【问题标题】:Parse XML document in Perl without knowing its structure在 Perl 中解析 XML 文档而不知道其结构
【发布时间】:2013-12-03 15:06:00
【问题描述】:

我是 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}) { };
}

【问题讨论】:

  • 您使用的是哪个模块(例如 XML dom)?另外,请考虑分享您迄今为止尝试过的 Perl 代码,即使它没有成功。
  • 您可以使用 XML::Simple 并遍历其输出。
  • XML::Simple 是最难使用的模块,特别是如果您事先不知道其结构(可以通过ForceArray => 1, KeyAttr => [] 缓解)

标签: xml perl xml-parsing


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这个怎么样:

    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);
    

    【讨论】:

    • 看起来不错,谢谢,但不幸的是它只列出了主要节点和属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2015-02-04
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多