|
XML::Simple Module
Part:
1
2
3
4
5
(Continued from previous part...)
"keyattr" Example - XmlSimpleKey.pl
keyattr => list: Applies to XMLin() and XMLout() to name attributes,
or sub-elements as keys to be used to promot the parent element from
array to hash. Remember that there is default list: "name", "key", and "id".
The following program shows you how to use option, keyattr:
#- XmlSimpleKey.pl
#- Copyright (c) 1999 by Dr. Herong Yang
#
use XML::Simple;
use Data::Dumper;
my $xs = new XML::Simple(keeproot => 1,searchpath => ".",
forcearray => 1); # default is: keyattr => [name, key, id])
my $ref = $xs->XMLin("bank.xml");
my $xml = $xs->XMLout($ref);
print "\nHash dump with 'keyattr => [name, key, id]':\n";
print Dumper($ref);
print "\nXML output with 'keyattr => [name, key, id]':\n";
print $xml;
my $xs = new XML::Simple(keeproot => 1,searchpath => ".",
forcearray => 1, keyattr => [key, tag]);
my $ref = $xs->XMLin("bank.xml");
my $xml = $xs->XMLout($ref);
print "\nHash dump with 'keyattr => [key, tag]':\n";
print Dumper($ref);
print "\nXML output with 'keyattr => [key, tag]':\n";
print $xml;
exit;
The input file, bank.xml, has the following XML:
<?xml version="1.0"?>
<bank>
<account id="123-4567">
<type>Checking</type>
<balance>149.99</balance>
</account>
<client>
<name>Mike Lee</name>
<email>mike@lee.com</email>
</client>
<account>
<id>333-4444</id>
<type>Saving</type>
<balance>941.99</balance>
</account>
</bank>
Here is the output of the program:
Hash dump with 'keyattr => [name, key, id]':
$VAR1 = {
'bank' => [
{
'account' => {
'ARRAY(0x26426ec)' => {
'type' => [
'Saving'
],
'balance' => [
'941.99'
]
},
'123-4567' => {
'type' => [
'Checking'
],
'balance' => [
'149.99'
]
}
},
'client' => {
'ARRAY(0x2642680)' => {
'email' => [
'mike@lee.com'
]
}
}
}
]
};
XML output with 'keyattr => [name, key, id]':
<bank>
<account name="ARRAY(0x26426ec)">
<type>Saving</type>
<balance>941.99</balance>
</account>
<account name="123-4567">
<type>Checking</type>
<balance>149.99</balance>
</account>
<client name="ARRAY(0x2642680)">
<email>mike@lee.com</email>
</client>
</bank>
Hash dump with 'keyattr => [key, tag]':
$VAR1 = {
'bank' => [
{
'account' => [
{
'id' => '123-4567',
'type' => [
'Checking'
],
'balance' => [
'149.99'
]
},
{
'id' => [
'333-4444'
],
'type' => [
'Saving'
],
'balance' => [
'941.99'
]
}
],
'client' => [
{
'email' => [
'mike@lee.com'
],
'name' => [
'Mike Lee'
]
}
]
}
]
};
XML output with 'keyattr => [key, tag]':
<bank>
<account id="123-4567">
<type>Checking</type>
<balance>149.99</balance>
</account>
<account>
<id>333-4444</id>
<type>Saving</type>
<balance>941.99</balance>
</account>
<client>
<email>mike@lee.com</email>
<name>Mike Lee</name>
</client>
</bank>
(Continued on next part...)
Part:
1
2
3
4
5
|