bimlesh sharma
bimlesh sharma

Reputation: 181

how to put xml string in html table cell using perl

I have xml message in a variable and want to display on browser using table. I tried below but during rendering to browser the actual xml string is not showing.

open FH, ">report.html";

my $x=qq(<?xml version="1.0" encoding="utf-8" ?>
<Soap-ENV:Envelope xmlns:Soap-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:msdwHdr="http://xml.xdft.com/ns/appmw/soap/1.0/header" version="1.1">
 <Soap-ENV:Body>
  <CheckTrade>
   <tradeId>492195</tradeId>
  </CheckTrade>
 </Soap-ENV:Body>
</Soap-ENV:Envelope>);

print FH "<table><tr><td>test</td><td>$x</td></tr></table>";

If i run above code and open report.html in browser i am able to see first TD value and in second TD it is showing only 492195 (that is part of tradeid) i want to see complete $x value. I looked at source of html.It is showing same as $x but on browser it is not.

______________
test  | 492195 
______|________ 

Upvotes: 1

Views: 251

Answers (2)

mirod
mirod

Reputation: 16171

You could also escape the entire XML string by putting it in a [CDATA][1] section:

print FH "<table><tr><td>test</td><td><![CDATA[$x]]></td></tr></table>";

Of course this works only as long as the SOAP message doesn't itself contain CDATA. If that happens, you will need to break it up: replace the CDATA end marker, ]]>, in the SOAP message by ]]]><![CDATA[]> (closing the CDATA section in the middle of the marker and starting a new one, that starts with the end of the marker:

$x=~ s{]]>}{]]]><![CDATA[]>}g;

or more clearly:

 $x=~ s{]]>}                   # CDATA end marker
       {]                      # beginning of the end marker
         ]]>                   # end the first CDATA section
            <![CDATA[          # start a new CDATA section
                     ]>}gx;    # end of the end marker

A couple of notes on your Perl style:

  • the current best practices are to avoid bareword filehandles, by using lexical ones,

  • it's also considered better to use the 3 args form of open, in your case likely with an encoding:

so it's probably better to write this:

open( my $fh, '>:utf8', 'report.html') or die "cannot open reports.html: $!";
...
print {$fh} "<table><tr><td>test</td><td><![CDATA[$x]]></td></tr></table>";

Upvotes: 2

Joel
Joel

Reputation: 3483

The issue that you're having is the XML document doesn't play nicely in HTML. All the <> characters confuse your browser and thus you're only getting the value of tradeID. Look at this answer for how to encode your XML string before you put it into the HTML document.

Upvotes: 2

Related Questions