http://qs321.pair.com?node_id=529462


in reply to XML Parse, Spanish Elements

Hi Senik,
Personnally I'm not such a big fan of XML::Simple since the parsing into different types is very unconfortable. For example if a node contains one subnode, the subnode is a hash element in the node itself, with nore children it becomes an array..this is just an example, but is just to show that the parsetree is very difficult to navigate.
Myself I rather use XML::XPath. Here you can use xpath queries to navigate to the nodes you want and the result is very straightforward.
for you this would become something like :
use XML::XPath; use XML::XPath::XMLParser; my $xp = XML::XPath->new(filename => 'test.xhtml'); my $nodeset = $xp->find('/noticias/noticia'); foreach my $noticia ($nodeset->get_nodelist) { my ($title,$fulltext,$date,$time) = ( $noticia->find('titulo')->string_value, $noticia->find('texto')->string_value, $noticia->find('fecha')->string_value, $noticia->find('hora')->string_value ) }
Hope this helps you, it saved my life more than once :)
--
Cheers,
Rob

Replies are listed 'Best First'.
Re^2: XML Parse, Spanish Elements
by jbrugger (Parson) on Feb 13, 2006 at 10:19 UTC
    I'm not such a big fan of XML::Simple since the parsing into different types is very unconfortable. For example if a node contains one subnode, the subnode is a hash element in the node itself,

    You can use use the argument ForeArray to overcome that problem:
    my $xs = new XML::Simple(ForceArray => 1); Now all elements are read as an array.

    "We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.
      Hi jbrugger, Does that also mean that it will return an array of arrays of arrays....?
      The downside of something like that is that you would have to use $xml->[3]->[3]->[1]->[2] structures to reference nodes from your XML file. So you have to use you knowledge about the structure of the XML file to be able to reference nodes. That feels unconfortable to me at least.
      The nice thing about XML::XPath is that you can use full xpath expressions like /document//element_somwhere[@att="val"]/../next-sibbling or anything like that.

      before this starts sounding like a sales-pitch for XML::XPath, I think users should just use what feels most confortable.
      --
      Cheers,
      Rob
        From the docs:
        ForceArray => 1 <opt> <name>value</name> </opt> would parse to this: { 'name' => [ 'value' ] } instead of this (the default): { 'name' => 'value' }
        "We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.