Unfortunately the suggestions offered to an earlier query did not work. I am trying to use Twig to split a file that has <MyConnectData> as the root and <Message> as the first child. My code below does work when there is only one <Message> element. When there is more than one <Message> element the error that is generated is:

Can't call method "text" on and undefined value at line 11.

I'm new enough at this that I need the simplest possbile explanation as to how I can use this code to read more than one <Message> element in the .xml file.

Thanks in advance.
--------------------------------------------- use XML::Twig;

my $field= $ARGV[0] || 'ppg';
my $twig= new XML::Twig;

$twig->parsefile( "mydata.xml");
my $root= $twig->root;
my @Messages= $root->children;


my @sorted= sort { $b->first_child( $field)->text
<=> $a->first_child( $field)->text }
@Messages;

print '<?xml version="1.0"?>';
print '<!DOCTYPE stats SYSTEM "stats.dtd" []>';
print '<MyConnectData>';

foreach my $Message (@sorted)
{ $Message->print;

open (fh, '>>F:/perl/datafiles/test.xml');
$twig->print(\*fh);
close fh;
}
print "</MyConnectData>\n";


In reply to Splitting XML file ... by xmlsql

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.