How can I escape text for an XML document in Perl?

前端 未结 9 1165
长发绾君心
长发绾君心 2021-01-01 06:53

Anyone know of any Perl module to escape text in an XML document?

I\'m generating XML which will contain text that was entered by the user. I want to correctly handl

相关标签:
9条回答
  • 2021-01-01 07:10

    Although you better use a module like XML::LibXML or XML::Code you could wrap textual data in a CDATA section. You must only take care not to put ]]> in it (this sequence is also disallowed outside of CDATA sections!):

    $text =~ s/\]\]>/]]>]]&gt;<![CDATA[/;
    $text = "<![CDATA[$text]]>";
    $xml = "<foo>$text</foo>"; 
    

    As bonus your code will look more perlish obfuscated! :-)

    0 讨论(0)
  • 2021-01-01 07:13

    I am not sure why you need to escape text that is in an XML file. If your file contains:

    <foo>x < y</foo>
    

    The file is not an XML file despite the proliferation of angle brackets. An XML file must contain valid data meaning something like this:

    <foo>x &lt; y</foo>
    

    or

    <foo><![CDATA[x < y]]></foo>
    

    Therefore, either:

    1. You are not asking for escaping data in an XML file. Rather, you want to figure out how to put character data in an XML file so the resulting file is valid XML; or

    2. You have some data in an XML file that needs to be escaped for some other reason.

    Care to elaborate?

    0 讨论(0)
  • 2021-01-01 07:19

    After checking out XML::Code as recommended by Krish I found that this can be done using the XML::Code text() function. E.g.,

    use XML::Code;
    my $text = new XML::Code('=');
    $text->set_text(q{> & < " ' "});
    print $text->code(); # prints &gt; &lt; &amp; " ' "
    

    Passing '=' creates a text node which when printed doesn't contain tags. Note: this only works for text data. It wont correctly escape attributes.

    0 讨论(0)
提交回复
热议问题