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 <![CDATA[http://www.123.42 1345&4686=userid:fs/fsfsf]></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 esc开发者_StackOverflowape the "<" character?
Are you sure your error doesn't come from the ampersand character &
? Try replacing it with &
For anything else, please post minimal code that exhibits the problem.
& is replaced by &
< is replaced by <
> is replaced by >
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<$2/g;
s/^(<.*>.*)>(.*<\/\S+>)$/$1>$2/g;
}
$content = join("\n",@lines);
the regex could be better.
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.
精彩评论