Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Formatting messed XML -document with Perl 1

Status
Not open for further replies.

comma

Programmer
Feb 12, 2003
24
FI
Hi!

I was wondering if there is convenient way to format messed xml-document with Perl.

Example:
<?xml version=&quot;1.0&quot;?>
<section>
<subchapter name=&quot;example&quot;>
<subdata name=&quot;exampledata&quot; id=&quot;0&quot; />
</subchapter>
</section>

should be formatted to form and written back to disk:

<?xml version=&quot;1.0&quot;?>
<section>
<subchapter name=&quot;example&quot;>
<subdata name=&quot;exampledata&quot; id=&quot;0&quot; />
</subchapter>
</section>

Do you have any example or hint on this?

Thank you!

BR,
comma
 
This is rough but should get you started:

[tt]#!/usr/bin/perl

use XML::parser;

$/=undef; # slurp mode
my $in = <STDIN>;
$in =~ s/>\s*</></g; # lose inter-tag spaces

$p1 = new XML::parser(Style => 'Tree');
my $tree = $p1->parse($in);
tree_print(0, $tree);

exit;

sub tree_print {
my( $level, $tree ) = @_;
while( @$tree ) {
my $a = shift @$tree;
my $b = shift @$tree;
if ( $a eq '0' ) { # node
print &quot;\t&quot; x $level, $b, &quot;\n&quot;;
} else { # element
my $attr = shift @$b;
my $attr_str = join( ' ', map {&quot;$_=$attr->{$_}&quot;} keys %$attr );
print &quot;\t&quot; x $level, &quot;<$a $attr_str>\n&quot;;
tree_print($level+1, $b);
print &quot;\t&quot; x $level, &quot;</$a>\n&quot;;
}
}
}
[/tt]

Good luck!
 
Hi!

Thank you! Your example is very good!

BR,
comma
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top