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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.