in reply to Re: perl & XML: getting last child?
in thread perl & XML: getting last child?
You can test what is returned from the text node. There is an xpath expression to do this also but I usually just test it like this. (untested code)
foreach ($doc->findnodes('/library/cd/artist/text()'){ my $artist = $_->data; if ($artist){ print "$artist | "; } else { print "0 | "; } }
If the artist was formerly called Prince I'm not sure whether Perl will evaluate that symbol to true or false, (or male or female)... it's a little confusing.
Update: The above won't work since findnodes() will only return the nodes that have text. I often have the situation where I need to add text to empty text nodes. Here is something closer.
foreach ($doc->findnodes('/library/cd/artist')){ #update: added ')' my $artist = $_->to_literal; if ($artist){ print "$artist | "; #to change the text use my $textnode=$_->findnodes('./text()') # then use $textnode->setData('new text'); } else { print "0 | "; # you can use $_->appendTextNode('text to add') here } }
Another option is to loop through seperately the nodes with no text using the not() funtion of xpath.
foreach ($doc->findnodes('/library/cd/artist[not(text())]'){
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: perl & XML: getting last child?
by ambrill (Novice) on Apr 24, 2013 at 01:57 UTC | |
by Lotus1 (Vicar) on Apr 24, 2013 at 14:27 UTC |