in reply to Re^2: XML Attribute vs Element
in thread XML Attribute vs Element

I'd use something simpler for parsing the XML than XML::Simple, like XML::Parser, although I don't know what you want the final output for so the rendering below may not suit you:

use warnings; use strict; use XML::Parser; my $xmlStr = <<XML; <A> <B> <C> <element type="k" name="p" online="yes"/> <element type="i" name="e" online="yes"/> </C> <D> <element type="kd" name="pd" online="no"/> <element type="id" name="ed" online="yes"/> <element type="yd" name="zd" online="no"/> </D> </B> <Z> <C> <element type="k" name="z" online="yes"/> <element type="t" name="p" online="yes"/> </C> <E> <element type="kd" name="pd" online="no"/> <element type="id" name="ed" online="yes"/> </E> </Z> </A> XML use constant kIndentSize => 4; my $indent = ''; my $xs1 = XML::Parser->new ( Handlers => { Start => sub {start (\$indent, @_);}, End => sub {end (\$indent, @_);}, Char => sub {char (\$indent, @_);} }); $xs1->parse ($xmlStr); sub start { my ($indent, $expat, $element, %attr) = @_; print "$$indent$element\n"; $$indent .= ' ' x kIndentSize; print "$$indent$_ : $attr{$_}\n" for sort keys %attr; return; } sub end { my ($indent, $expat, $element) = @_; substr $$indent, -(kIndentSize), kIndentSize, ''; return; } sub char { my ($indent, $expat, $string) = @_; chomp $string; $string =~ s/^\s+|\s+$//g; return unless length $string; print "$$indent$string\n"; return; }

Prints:

A B C element name : p online : yes type : k element name : e online : yes type : i D element name : pd online : no type : kd element name : ed online : yes type : id element name : zd online : no type : yd Z C element name : z online : yes type : k element name : p online : yes type : t E element name : pd online : no type : kd element name : ed online : yes type : id

Perl reduces RSI - it saves typing

Replies are listed 'Best First'.
Re^4: XML Attribute vs Element
by Sporti69 (Acolyte) on Nov 07, 2008 at 12:14 UTC