For practice I made a simple xml file, and I want to read it into a perl script. I think I should be using either XML::Parser or XML::LibXML
The second choice seems to be easier, but I can't get it to work.
XML::Parser is just confusing, even after reading a tutorial. Which should I be using, a stream or a style?
Basically, I want to be able to get a list of all race->name's and then later, I will want to get elements within race->name(if eq to the race name the user chose) If I have the following file (easier on the eyes: races.xml)
code:
<?xml version="1.0" encoding="ISO-8859-1"?>
<racedata>
<race>
<name>human</name>
<str>0</str>
<dex>0</dex>
<con>0</con>
<int>0</int>
<wis>0</wis>
<cha>0</cha>
</race>
<race>
<name>dwarf</name>
<str>0</str>
<dex>0</dex>
<con>2</con>
<int>0</int>
<wis>0</wis>
<cha>-2</cha>
</race>
<! -- some more data 7 total races -->
</racedata>
I've already read through "perldoc XML::Parser" but it didn't help me understand how to use it.
Then I tried XML::LibXML (which had about 3 or 4 dependancies, is it less common to be installed?) but this script doesn't work:
code:
#!/usr/bin/perl -w
use strict;
use XML::LibXML;
sub xml_print
{
my $file_path = "./${dir_data}/races.xml";
my $parser = XML::LibXML->new();
my $tree = $parser->parse_file($file_path);
my $root = $tree->getDocumentElement;
my @races = $root->getElementsByTagName('race');
foreach my $cur_node (@races)
{
my $cur_race;
if($cur_node->hasAttribute('name'))
{
$cur_race = $cur_node->getAttribute('name');
print "${cur_race}\n";
}
{
print "does not have attribute\n";
}
my @nodes = $cur_node->getChildrenByTagName('name');
foreach $_ (@nodes)
{
print "$_\n";
}
}
}
&xml_print;
and this is what I get as output
code:
does not have attribute
XML::LibXML::Element=SCALAR(0x8264488)
does not have attribute
XML::LibXML::Element=SCALAR(0x82643c8)
does not have attribute
XML::LibXML::Element=SCALAR(0x8264794)
does not have attribute
XML::LibXML::Element=SCALAR(0x8264788)
does not have attribute
XML::LibXML::Element=SCALAR(0x826477c)
does not have attribute
XML::LibXML::Element=SCALAR(0x8264770)
does not have attribute
XML::LibXML::Element=SCALAR(0x8264764)
I think this is what is happening @races is an array of the elements that have the tag name 'races' and from their I need to get the child element 'name' and get the text within that element. I don't think I want attribute because I think attribute is inside a tag which is part of an element.
thanks,
--monkey
[This message has been edited by ninmonkey (edited 01-08-2004).]