3

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.

tacoscool
  • 83
  • 1
  • 2
  • 7

9 Answers9

11

The XML::Simple escape_value could be used also, but use of XML::Simple is not recommended for new programs. See this post post 17436965.

A manual escape could be done using regex (copied from escape_value):

$data =~ s/&/&/sg;
$data =~ s/</&lt;/sg;
$data =~ s/>/&gt;/sg;
$data =~ s/"/&quot;/sg;
Wadester
  • 343
  • 2
  • 5
9

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:

use XML::LibXML;
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.

Wadester
  • 343
  • 2
  • 5
zakovyrya
  • 9,579
  • 6
  • 39
  • 28
  • 1
    Point taken. I shouldn't have created the XML by hand (they were simple XML documents when I started). I'll need to get around to rewriting those bits of code. – tacoscool Jul 17 '09 at 11:08
  • I've accepted this answer not for the XML::LibXML recommendation (I used XML::Writer) but for pointing out that it is not good practice to create XML by hand. – tacoscool Jul 28 '09 at 13:27
  • 1
    Note that XML::LibXML has non-perl dependencies and might not readily install on your platform. – muenalan Mar 30 '15 at 18:22
  • you're missing `$doc->setDocumentElement($element);` if you want to get everything in – arhak Jul 15 '16 at 10:18
8

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?

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • 2
    People get mad when you remind them that their pseudo-XML is not actually real XML. It is amusing... and sad. Anyway, I upvoted you :) – jrockway Jul 16 '09 at 20:29
  • My question would be #1. I didn't realise my question wasn't clear. I'll update the question to clarify. – tacoscool Jul 16 '09 at 23:04
  • here my case is I am putting one XML inside another SOAP, and the soap parser have problem parsing the encapsulated message. – zinking May 23 '14 at 04:08
  • 1
    Useless non-answer. Yes, the original question was not very clear, but it was still easy to guess, or you could have asked for clarification. I understnad your point, but it would come across better if it were with a useful answer (like most other answers on this page). – mivk Sep 01 '18 at 18:47
6

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 ("&#8212;");
        $p->escape (0);
        print $p->code(); # prints <p>&#8212;</p>
        $p->escape (1);
        print $p->code(); # prints <p>&amp;#8212;</p>
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
joe
  • 34,529
  • 29
  • 100
  • 137
3

XML::Entities:

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

hovenko
  • 713
  • 7
  • 15
3

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).

muenalan
  • 588
  • 4
  • 8
1

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.

tacoscool
  • 83
  • 1
  • 2
  • 7
0

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! :-)

Jakob
  • 3,570
  • 3
  • 36
  • 49
0

For programs that need to handle every special case, by all means use an official library for this task. However, theoretically there are only 5 characters that need escaping in XML.

So, for one-offs that you don't want to pull in an extra library for, the following perl expression should suffice:

perl -pe 's/\&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'"'"'/\&apos;/g'
Raman
  • 17,606
  • 5
  • 95
  • 112