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())]'){In reply to Re^2: perl & XML: getting last child?
by Lotus1
in thread perl & XML: getting last child?
by ambrill
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |