XML::Simple

XML::Simple - Easy API to maintain XML (esp config files)

  • 可正常透過 perl -MCPAN -e shell 安裝
  • 執行時會出現 could not find ParserDetails.ini 訊息, 可透過以下語法解決

    perl -MXML::SAX -e "XML::SAX->add_parser(q(XML::SAX::PurePerl))->save_parsers()"

#!/usr/bin/perl
 
use XML::Simple qw(:strict);
 
$ref = XMLin('/tmp/t.xml',
    ForceArray => 1,
    KeyAttr    => {},
);
 
$receiverlist=$ref->{receiverlist}[0];
$i=0;
foreach $receiverinfo (@{$receiverlist->{object}}) {
        $i++;
        print("$i:");
        $orgid=$receiverinfo->{orgid}[0];
        $unitid=ref($receiverinfo->{unitid}[0]) eq "HASH"?"":$receiverinfo->{unitid}[0];
        print("[$orgid$unitid]\n");
}
exit;

/tmp/t.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE g2b2c-envelope SYSTEM "envelope.dtd">
<g2b2c-envelope>
:
:
<receiverlist>
<object type="addressbook">
<orgid>341000000A</orgid>
<unitid>U000020</unitid>
<orgname>行政院研究發展考核委員會</orgname>
<note></note>
</object>
<object type="addressbook">
<orgid>313000000G</orgid>
<unitid></unitid>
<orgname>經濟部</orgname>
<note></note>
</object>
</receiverlist>
:
:
</g2b2c-envelope>

執行結果

[root@rdtest02 tmp]# perl t1.pl
1:[341000000AU000020]
2:[313000000G]
安裝 XML::LibXML 過程出現找不到 libxml2 的問題, 但在 CentOS 內已經安裝完成 libxml2 以及 libxml2-devel 套件, 所以就放棄使用 XML::LibXML 這模組.
  • tech/perl/xml_simple.txt
  • 上一次變更: 2021/01/16 14:38
  • jonathan