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 handle the text so that the resulting XML is well formed.
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 handle the text so that the resulting XML is well formed.
Use XML::Code.
From CPAN
XML::code escape()
Normally any content of the node will be escaped during rendering (i. e. special symbols like '&' will be replaced by corresponding entities). Call escape() with zero argument to prevent it:
my $p = XML::Code->('p');
$p->set_text ("—");
$p->escape (0);
print $p->code(); # prints <p>—</p>
$p->escape (1);
print $p->code(); # prints <p>&#8212;</p>
use XML::Entities;
my $a_encoded = XML::Entities::numify('all', $a);
Edit: XML::Entities only numifies HTML entities. Use HTML::Entities encode_entities($a) instead
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 < y</foo>
or
<foo><![CDATA[x < y]]></foo>
Therefore, either:
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
You have some data in an XML file that needs to be escaped for some other reason.
Care to elaborate?
I personally prefer XML::LibXML - Perl binding for libxml. One of the pros - it uses one of the fastest XML processing library available. Here is an example for creating text node:
my $doc = XML::LibXML:Document->new('1.0',$some_encoding);
my $element = $doc->createElement($name);
$element->appendText($text);
$xml_fragment = $element->toString();
$xml_document = $doc->toString();
And, never, ever create XML by hand. It's gonna be bad for your health when people find out what you did.
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 > < & " ' "
Passing '=' creates a text node which when printed doesn't contain tags. Note: this only works for text data. It wont correctly escape attributes.
Use
XML::Generator
require XML::Generator;
my $xml = XML::Generator->new( ':pretty', escape => 'always,apos' );
print $xml->h1( " &< >non-html plain text< >&" );
which will print all content inside the tags escaped (no conflicts with the markup).