shamu has asked for the wisdom of the Perl Monks concerning the following question:

How does one retrieve just an element's text ($elt->text) without retrieving that element's children's text in XML::Twig?

Replies are listed 'Best First'.
Re: Get text without children in XML::Twig
by mirod (Canon) on Dec 07, 2006 at 14:47 UTC

    Well at the moment you can't, but if you give me a good name for the method, I'll add it to the module.

    In the meantime, you can do (untested):

    my $text= join '', map { $_->text if( $_->is_text) } $elt->children;
      Howdy!

      How about a different approach:

      my $text = $elt->text('-nochildren');
      or some such argument. Are there other methods that might benefit from the same treatment? Would that make more sense than adding a new method, or would that not fit with the general way that XML::Twig works?

      yours,
      Michael

        It does make sense. There are a few methods that could use this argument. Thanks for the idea.

      root_text()


      DWIM is Perl's answer to Gödel

        I am not sure about this one. root is usually reserved for the root of the tree. I would expect root_text to give me the text of the root of the tree (ie whitout the XML declaration and comments/PIs before the root).

        What about text_only? I like the idea of the method being named text_..., so it is obviuus that it returns the text, and so it appears right after text in the online doc ToC, which is sorted by alphabetical order.

Re: Get text without children in XML::Twig
by shamu (Acolyte) on Dec 11, 2006 at 16:07 UTC
    Or use the conventional norecurse already used throughout XML::Twig.