hacker has asked for the wisdom of the Perl Monks concerning the following question:
My input data looks like this:
<document> <stayonhost>1</stayonhost> <staybelow>1</staybelow> <maxdepth>2</maxdepth> <name>Swedish Foo</name> <home_url>http://www.foo.se/bar/</home_url> <category>International</category> [... up to 40 other element pairs..] </document>
Here's what I have thus far (featuring the snazzy new 2003 floor model PM indenting!):
use strict; # er, um, I forgot use DBI; # for storing in SQL use XML::DOM; # roll through the nodes # XML pre-requisites my $file = "funkyapp.xml"; my $xp = new XML::DOM::Parser(); my $doc = $xp->parsefile($file); my $root = $doc->getDocumentElement(); my @nodes = $root->getChildNodes(); foreach my $node (@nodes) { # get child nodes (yes, "childs") if ($node->getNodeType() == 1) { # check element name foreach my $item (@childs) { if ($node->getNodeType() == 1) { my @childs = $node->getChildNodes(); # iterate through child nodes foreach my $item (@childs) { # check element name ################################################# if (lc($item->getNodeName) eq "name") { my $name = $item->getFirstChild()->getData; ################################################# } elsif (lc($item->getNodeName) eq "home_url") { my $url = $item->getFirstChild()->getData; ################################################# } elsif (lc($item->getNodeName) eq "stayonhost") { my $stayhost = $item->getFirstChild()->getData; ################################################# } elsif (lc($item->getNodeName) eq "staybelow") { my $staybelow = $item->getFirstChild()->getData; ################################################# } elsif (lc($item->getNodeName) eq "maxdepth") { my $maxdepth = $item->getFirstChild()->getData; } # elsif { # [... 40 other nodes.. ] } # Insert values into SQL here, this works } }
This code works, and prints/stores the values I expect in the database, but it gets very repititious trying to add new nodes, and duplicating the code over and over.
The issue I'd like to solve here is that this input file could have about 40 different nodeName values. I'd like to eliminate the repetition of the code seen above to do this. Is there a simpler way to do that, and still give me the ability to print/store the values by name?
Update: added a description of my input data (thanks jeffa for the reminder)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Rolling in the sheets with XML
by gjb (Vicar) on Apr 30, 2003 at 12:59 UTC | |
by Anonymous Monk on Apr 30, 2003 at 13:56 UTC | |
|
(jeffa) Re: Rolling in the sheets with XML
by jeffa (Bishop) on Apr 30, 2003 at 17:59 UTC |