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
    I cannot get your code to work. Any ideas? thanks

      Typically I look at the warnings and errors and fix any problems until the code will run. Then I look at the output to see if I'm getting the expected results and make changes and read the documentation for any modules or functions that aren't working like I expect. I also put in extra print statements to test my assumptions of how the code should work.

      The code I posted has a missing parenthesis but otherwise does what you requested. The second warning message points you to the exact line where this occurs.

      syntax error at C:\b\perlmonks\xml\1029217.pl line __, near "){"