Desai
Desai

Reputation: 187

Escaping "<" in Perl-generated XML

I need to generate an XML output using Perl code. I'm trying not to use any libraries, as it's very simple, temporary XML that gets used by another step in the process.

Through my perl code I needed to write something like "url http://www.123.42 1345&4686=userid:fs/fsfsf" which resulted in a parser error, and the following XML output:

<text>url http://www.123.42 1345&4686=userid:fs/fsfsf  </text>

So I attempted to write "url \<![CDATA[<http://www.123.42 1345&4686=userid:fs/fsfsf]\>" but that also resulted in a parser error and the following output:

<text>URL &lt;![CDATA[http://www.123.42 1345&4686=userid:fs/fsfsf]&gt;</text>

I'd like to get this:

<text>URL <![CDATA[http://www.123.42 1345&4686=userid:fs/fsfsf]></text>

How can I make the XML escape the "<" character?

Upvotes: 0

Views: 503

Answers (4)

Tel
Tel

Reputation: 227

Three people have said "use a library" but not one of them has answered the question demonstrating how a library could be used for this problem. That is why everyone hates XML so much, because the libraries are insanely cumbersome and unsuable.

sub make_cdata
{
        my $x = shift;
        $x =~ s{]]>}{]]]]><![CDATA[>}g;
        return( "<![CDATA[$x]]>" );
}

It is appallingly ugly XML.

I'll give an even better answer, use JSON.

Upvotes: 0

wesyoung
wesyoung

Reputation: 11

it's not perfect, but it's a start:

my $rss = XML::RSS->new();
my @lines = split("\n",$content);
foreach(@lines){
    s/(\S+)<(.*<\/\S+>)$/$1&#x3c;$2/g;
    s/^(<.*>.*)>(.*<\/\S+>)$/$1&#x3e;$2/g;
}
$content = join("\n",@lines);

the regex could be better.

Upvotes: 1

Francisco R
Francisco R

Reputation: 4048

& is replaced by &#x26;
< is replaced by &#x3c;
> is replaced by &#x3e;

Upvotes: 1

JB.
JB.

Reputation: 42104

Are you sure your error doesn't come from the ampersand character & ? Try replacing it with &amp;

For anything else, please post minimal code that exhibits the problem.

Upvotes: 5

Related Questions