Fellow Monks,
After a lot of documentation reading and testing and spending almost 2 days trying to understand XML:Parser module I finally have to ask for some help here.
I receive some data in a XML file and am required to extract part of the data
<rootNode>
<a>
...text + other XML
</a>
<a>
...text + other XML
</a>
</rootNode>
Now I need to extract all information between
<a> and </a>
tags and I need to do this using XML:Parser.
Any suggestions on how I could do this ?
below is my non-working code:
===============================================
use XML::Parser;
my $XmlFile = "foo.xml";
die "Can't find file \"$XmlFile\"" unless -f $XmlFile;
my $pFoundFlag = 0;
my $NewFile;
my $parser = new XML::Parser(Style => 'Debug');
$parser->setHandlers( Start => \&startElement(),
Char => \&char_handler(),
End => \&end_Handler,
);
$parser->parsefile($XmlFile);
sub startElement {
my ($parserInst, $element, %attr) = @_;
if ($element eq "a") {
$pFoundFlag = 1;
}
if ($pFoundFlag) {
if(not $NewFile) {
$NewFile = $element;
} else {
$NewFile .= $element;
}
}
}
sub char_handler {
my ($parserInst, $data);
if ($pFoundFlag) {
$NewFile .= $data;
}
}
sub end_Handler {
my ($parserInst, $element);
if ($pFoundFlag) {
$NewFile .= $element;
}
if ($element eq "a") {
$pFoundFlag = 0;
}
}
$OpFile = "foo_outpur.xml";
open (OP, ">$OpFile") or die ("can't open output file!");
print OP $NewFile;
close(OP);
================================================
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.