in reply to Re^2: XML Attribute vs Element
in thread XML Attribute vs Element
When I add an attribute to lets say tag B...
You are getting the error message because XML::Simple creates a data structure with an array for your elements but a simple scalar value for your attribute.
You can see this if you use Data::Dumper to dump $doc after loading your file.
After changing your B tag to <B type="xxx"> your script produced the following error: Can't use string ("xxx") as an ARRAY ref while "strict refs" in use. Here is the structure produced by XMLin:
$VAR1 = { 'Z' => [ { 'C' => [ { 'element' => [ { 'name' => 'z', 'type' => 'k', 'online' => 'yes' }, { 'name' => 'p', 'type' => 't', 'online' => 'yes' } ] } ], 'E' => [ { 'element' => [ { 'name' => 'pd', 'type' => 'kd', 'online' => 'no' }, { 'name' => 'ed', 'type' => 'id', 'online' => 'yes' } ] } ] } ], 'B' => [ { 'D' => [ { 'element' => [ { 'name' => 'pd', 'type' => 'kd', 'online' => 'no' }, { 'name' => 'ed', 'type' => 'id', 'online' => 'yes' }, { 'name' => 'zd', 'type' => 'yd', 'online' => 'no' } ] } ], 'C' => [ { 'element' => [ { 'name' => 'p', 'type' => 'k', 'online' => 'yes' }, { 'name' => 'e', 'type' => 'i', 'online' => 'yes' } ] } ], 'type' => 'xxx' } ] };
If you look carefully at what has been created for your tag B, you will see that there are three elements in the contained hash, with keys D, C and type. The values of the first two (D and C) are references to arrays but the value of the third is a string. Your program uses all three as if they were references to arrays. Because you have used use strict; (which is a good thing) perl stops when it gets to the string and reports the error.
You can either write your program to check whether a value is a reference or not, using ref or you can provide parameters to XML::Simple to make it load the elements and tags consistently. Which approach is better will depend on what you are doing. You may want to learn both methods so you can decide which is most appropriate.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: XML Attribute vs Element
by Sporti69 (Acolyte) on Nov 07, 2008 at 10:19 UTC |