How to parse XML and create a tree structure in Perl

烈酒焚心 提交于 2019-11-30 18:27:42

问题


I am parsing a XML file with XML::Simple. Is there any way to get a tree form from the XML? If so please explain with example or suggest a CPAN package.

I would like to know which tag I have to process after column and so on.

There is no sequence for the tags. The column tag can appear after Table or display_name many times.

Tab
    column
    Table
        column
    display_name
    column
    display_name

XML:

<Tab>
    <column>
        <display_name>xyz</display_name>
        <display_name>pqr</display_name>
    </column>
    <Table>
        <column><display_name>Department</display_name></column>
    </Table>
    <display_name>abc</display_name>
    <column>pwd</column>
    <display_name>jack</display_name>
</Tab>

output with XML::Simple:

$VAR1 = {
  'Table' => {
    'column' => {
      'display_name' => 'Department'
    }
  },
  'display_name' => [
    'abc',
    'jack'
  ],
  'column' => [
    {
      'display_name' => [
        'xyz',
        'pqr'
      ]
    },
    'pwd'
  ]
};

Expected o/p:

$VAR1 = {
  'column' => {
    'display_name' => [
      'xyz',
      'pqr'
    ]
  }
  'Table' => {
    'column' => {
      'display_name' => 'Department'
    }
  }, 
  'display_name' => 'abc',
  'column' => 'pwd',
  'display_name' =>'jack'
};

I know a hash with same keys isn't possible. Please suggest a way that I can maintain the sequence of tags and will be able to print them.


回答1:


XML::LibXML creates a tree with no loss of information.

use XML::LibXML qw( );
my $parser = XML::LibXML->new();
my $tree = $parser->parse_file($qfn);

You can generate the output you specified from there. (I don't know why you'd want to, since the Perl code you want for output would lose data if run.)




回答2:


I used XML::Parser for same file

#!/usr/sbin/perl
use  XML::Parser;
use Data::Dumper;
use strict;

my $Filename = "abc.xml";

my $Parser = new XML::Parser( Style => 'tree' );

my $Tree = $Parser->parsefile( $Filename );

print Dumper( $Tree );

If there is another way to get desired output please suggest.



来源:https://stackoverflow.com/questions/16746404/how-to-parse-xml-and-create-a-tree-structure-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!