Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Help with attributes and XML::Simple

by ig (Vicar)
on Aug 01, 2012 at 08:42 UTC ( #984733=note: print w/replies, xml ) Need Help??

in reply to Help with attributes and XML::Simple

In my experience, XML::Simple makes dealing with very simple XML simple but it makes dealing with more complex XML quite difficult. Had you spent two days learning one of the alternatives (I use XML::LibXML almost exclusively these days, but there are other very capable modules that give you good control over both parsing and generation of XML files) you could probably have solved your problem and learned a more powerful tool for future work.

In summary, my suggestion is to use XML::Simple if it does what you need by default or you can tweak it in a few minutes. Otherwise, invest in learning a more general/powerful tool.


As an example of one way to get your hash with XML::LibXML:

use strict; use warnings; use XML::LibXML; use Data::Dumper; my $xml = do { local $/; <DATA> }; my $dom = XML::LibXML->load_xml(string => $xml); my %vendors = map { $_->getAttribute('vendorUniqueKey') => $_->getAttribute('name') } @{$dom->getElementsByTagName('Vendor')}; print Dumper(\%vendors); __DATA__ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Import format="3.0" fileId="54630000-3141-1404-4310-7F0000014030" fil +eCreationDateTime="2012-07-23T06:04:31.415" catalogSource="TLCMz"> <Catalog> <Vendors> <Vendor name="Allen Systems" vendorUniqueKey="ALLENGRP"/> <Vendor name="Aonix North America" vendorUniqueKey="AONIX"/> <Vendor name="Beta Systems Software" vendorUniqueKey="BETASY +S"/> <Vendor name="BMC Software" vendorUniqueKey="BMC"/> </Vendors> </Catalog> </Import>


$VAR1 = { 'BETASYS' => 'Beta Systems Software', 'BMC' => 'BMC Software', 'ALLENGRP' => 'Allen Systems', 'AONIX' => 'Aonix North America' };

That's simple enough. The problem is, reading all the XML::LibXML docs (there are many) to find out how to do this isn't so simple.

Replies are listed 'Best First'.
Re^2: Help with attributes and XML::Simple
by tobyink (Abbot) on Aug 01, 2012 at 10:02 UTC

    If you've got a reasonably recent version of XML::LibXML, that can be made even simpler.

    use XML::LibXML 1.94; use Data::Dumper; my %hash = XML::LibXML -> load_xml(location => 'mydata.xml') -> getElementsByTagName('Vendor') -> map(sub { $_->{vendorUniqueKey} => $_->{name} }); print Dumper \%hash;
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://984733]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2017-10-20 06:12 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (259 votes). Check out past polls.