The following appears that it might do what you want. Note though that it will *not* work if you have cdata and elements mixed together.

#!/usr/bin/perl
use strict;
use HTML::Entities qw(encode_entities);
$| = 1;

my $str = "<Root>
  <Node1>Data with < in it</Node1>
  <Node2>Data with > in it</Node2>
  <Node3>
      <SubNode1>'one'</SubNode1>
      <SubNode2><\"two\"></SubNode2>
  </Node3>
</Root>";

Match($str);

sub Match
{
    my $str = shift;
    my $c = shift || 0;
    while ($str =~ m!<(_a-zA-Z0-9+)>(.+?)</\1>!sg)
    {
	my $tag = $1;
	my $tmp = $2;
	printf("%s<$tag>\n", "\t" x $c);
	# If there are subelements, recurse, otherwise,
	# just encode and print the data.
	if ($tmp =~ m!<(_a-zA-Z0-9+)>(.+?)</\1>!)
	{
	    Match($tmp, $c + 1);
	}
	else
	{
	    $tmp = encode_entities($tmp);
	    printf("%s$tmp\n", "\t" x ($c + 1));
	}
	printf("%s</$tag>\n", "\t" x $c);
    }
}

Outputs:

<Root>
        <Node1>
                Data with &lt; in it
        </Node1>
        <Node2>
                Data with &gt; in it
        </Node2>
        <Node3>
                <SubNode1>
                        'one'
                </SubNode1>
                <SubNode2>
                        &lt;&quot;two&quot;&gt;
                </SubNode2>
        </Node3>
</Root>

(Edited for formatting)


In reply to Re: Escaping XML Reserved characters by stingray
in thread Escaping XML Reserved characters by skinnymofo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.