Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm sending XML packets based on database results. I need to escape characters which screw up XML such as & and so on. Is there a module I can use to safely do this for my variables? Thanks
  • Comment on XML - Escaping characters from database for XML

Replies are listed 'Best First'.
Re: XML - Escaping characters from database for XML
by choroba (Cardinal) on May 28, 2012 at 12:32 UTC
    For example, XML::LibXML:
    use strict; use warnings; use feature 'say'; use XML::LibXML; my $xml = XML::LibXML->createDocument(); my $r = $xml->createElement('root'); $xml->setDocumentElement($r); $r->addChild($xml->createTextNode('<&')); say $xml->toString;
    Or its wrapper, XML::XSH2:
    create root ; insert text '<&' into /root ; ls . ;

      With XML::LibXML, you can get away without creating a document and element...

      print XML::LibXML::Text->new('<&')->toString;

      It's pretty easy to wrap that up into a function:

      sub escape_xml { XML::LibXML::Text->new(shift)->toString } print escape_xml('<&');
      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
        Well, yes. I was just discreetly suggesting creating the whole packages in XML::LibXML.