#!/perl -w
# NAME: xmlwrap03.pl
# AIM: Exploring XML::Parser::Wrapper, loading from file ...
# specifically parsing a MSVC8 VCPROJ file
# 28/07/2008 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use XML::Parser::Wrapper;
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
    my @tmpsp = split(/\\/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = "temp.$pgmname.txt";
open_log($outfile);

my $in_file = 'test.vcproj';
prt( "$0 ... Hello, World ... exploring XML::Parser::Wrapper\n" );
prt( "from: http://search.cpan.org/~dowens/XML-Parser-Wrapper-0.08/lib/XML/Parser/Wrapper.pm\n" );

my $parser = XML::Parser::Wrapper->new;
my $root3 = $parser->parse({ file => $in_file });
my ($tag, $type, $element, $childs, $isele, $ne, $atts, $att);
my $root_tag_name = $root3->name;
my $roots_children = $root3->elements;
prt( "root tag name = $root_tag_name ...\n" );
my $xcnt = 0;
foreach $element (@$roots_children) {
    $xcnt++;
    $isele = 0;
    if ($element->is_text()) {
        $tag = trim_all($element->text());
        $type = 'TEXT';
    } else {
        $tag = $element->name();
        $type = 'element name';
        $isele = 1;
    }
    if (length($tag)) {
        prt( "$xcnt: $type = $tag\n" );
    } else {
        ###prt( "$xcnt: $type = <all spacey>\n" );
    }
    if ($isele) {
        $atts = $element->attributes();
        foreach $att (keys %$atts) {
            prt( " attr $att=".$$atts{$att}."\n" );
        }
        process_element(1, " ",$element);
    }
}

my $nxml = '<?xml version="1.0" encoding="Windows-1252"?>'."\n";
$nxml .= $root3->to_xml;
$nxml .= "\n";

write2file($nxml, "tempxml.xml");
prt( "XML written to tempxml.xml ...\n" );

close_log($outfile,1);
exit(0);

sub process_element {
    my ($lev,$ind,$ele) = @_;
    my $ch = $ele->elements();
    my ($tx, $ats, $at, $tg);
    foreach my $itm (@$ch) {
        if ($itm->is_text()) {
            $tx = trim_all($itm->text());
            prt( "$ind Txt = $tx\n" ) if length($tx);
        } else {
            $tg = $itm->name();
            prt( "$ind Sub [$tg]($lev)\n" );
            $ats = $itm->attributes();
            foreach $at (keys %$ats) {
                prt( "$ind  Att $at=[".$$ats{$at}."]\n" );
            }
            process_element( ($lev + 1), "$ind  ", $itm );
        }
    }
}

# eof
