如何使用 CGI Perl 在 HTML table 中呈现 xml 内容

How to render xml content in a HTML table using CGI Perl

我正在尝试使用 CGI Perl 在简单的 HTML table 中显示 XML 内容(这是一个 SOAP 请求)。但是,XML 内容在内部被截断了 table 单元格。任何人都可以提出一个解决方案来正确呈现 XML HTML 页面?

下面是代码:

use strict;

use CGI;
use CGI::Carp qw(fatalsToBrowser);

my $qry = new CGI;

&show_html();


sub show_html {
    $qry->header();
    $qry->start_html(-bgcolor=>'#FFFFFF', -title=>'Rendering XML');
    my $body = &display_page();
    print $body;

    $qry->end_html;
}

sub display_page {

    my $html = qq{
        <table border="1">
        <tr>
            <th> Key </th>
            <th>Value</th>
        </tr>
        <tr>
            <td> SOAP </td>
            <td>POST /Quotation HTTP/1.0 Host: www.demohost Content-Type: text/xml; charset=utf-8 Content-Length: nnn  <?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.demourl1/2001/12/soap-envelope" SOAP-ENV:encodingStyle="http://www.demourl2/2001/12/soap-encoding" >     <SOAP-ENV:Body xmlns:m="http://www.demourl3/quotations" >              <m:GetQuotation>          <m:QuotationsName>MiscroSoft</m:QuotationsName>       </m:GetQuotation>                  </SOAP-ENV:Body>      </SOAP-ENV:Envelope>
            </td>
        </tr>
        </table>
    };
    return $html;

}

XML 充满了 <& 这样的字符,在 HTML.

中具有特殊含义

您需要对它们进行编码。

通常使用 the HTML::Entities module

use HTML::Entities;
my $html_encoded_string = encode_entities($raw_xml_string);

或者,使用支持 HTML 过滤的模板语言。

例如,在 Template-Toolkit 中,您可以执行以下操作:

<td>[% raw_xml_string | html %]</td>

您也可以使用 CGI.pm 的 HTML 生成函数(就像您在 show_html 中所做的那样,但是它们被标记为 HTML Generation functions should no longer be used 所以您真的应该 停止show_html中使用它们。

CGI.pm 文档推荐使用模板方法。