If I understand correctly you want to extract the text and its enclosing tag if it has one, and just the text if it doesn't. This might help:
use XML::LibXML;
my $xml = q|
<seg>
<foo mid="0" mtype="seg">
<g id="1">Need to export this text</g>
</foo>
<foo mid="1" mtype="seg">
Need to export this text also
</foo>
</seg>|;
my $doc = XML::LibXML->load_xml(string => $xml);
my @foos = $doc->findnodes('//foo');
for my $foo (@foos) {
my $mid = $foo->getAttribute('mid');
print "mid: $mid ";
my @childnodes = $foo->childNodes();
if (@childnodes) {
for my $node (@childnodes) {
print $node->toString, "\n";
}
}
else {
print $foo->textContent, "\n";
}
}
Output:
mid: 0
<g id="1">Need to export this text</g>
mid: 1
Need to export this text also
You may need to trim leading and trailing whitespace if your XML contains it.