开发者

Escaping "<" in Perl-generated XML

开发者 https://www.devze.com 2023-02-14 18:10 出处:网络
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.

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 esc开发者_StackOverflowape the "<" character?


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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号