且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Perl 脚本创建和填充复杂的 XML

更新时间:2022-03-03 09:25:05

首先,非常非常重要的概念:没有XML 模板"这样的东西!使用 XML 的全部意义在于能够根据一些模式读/写数据.如果您有(一致的)XML 示例但没有模式定义 (XSD),请使用 trang弄清楚:

First, the very, very important concept: there is no such thing as "XML template"! The whole point of using XML is being capable to read/write data according to some schema. If you have a (consistent) XML sample but no schema definition (XSD), use trang to figure it out:

java -jar trang.jar sample.xml sample.xsd

对于提供的示例,生成的 XSD 文件如下所示:

For provided sample, the generated XSD file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="TumorDetails">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="personUpi"/>
        <xs:element ref="ageAtDiagnosis"/>
        <xs:element ref="biopsyPathologyReportSummary"/>
        <xs:element ref="primarySiteCollection"/>
        <xs:element ref="distantMetastasisSite"/>
        <xs:element ref="siteGroup"/>
        <xs:element ref="tmStaging"/>
        <xs:element ref="pediatricStaging"/>
        <xs:element ref="histologicTypeCollection"/>
        <xs:element ref="histologicGradeCollection"/>
        <xs:element ref="familyHistoryCollection"/>
        <xs:element ref="comorbidityOrComplicationCollection"/>
        <xs:element ref="tumorBiomarkerTest"/>
        <xs:element ref="patientHistoryCollection"/>
        <xs:element ref="tumorHistory"/>
        <xs:element ref="placeOfDiagnosis"/>
        <xs:element ref="followUp"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
...
</xs:schema>

现在,***的部分称为 XML::Compile.它采用您的 XSD 模式,对其进行编译并适合/验证本机 Perl 结构,生成 XML 作为输出:

And now, the best part, called XML::Compile. It takes your XSD schema, compiles it and fits/validates native Perl structures, producing XML as an output:

#!/usr/bin/env perl
use strict;
use warnings;
use XML::Compile::Schema;

my $node = {
    personUpi                    => 'String',
    ageAtDiagnosis               => '3.14159E0',
    biopsyPathologyReportSummary => 'String',
    primarySiteCollection        => {
        tissueSite => {
            description => 'String',
            name        => 'String',
        },
    },
    ...
};

my $schema = XML::Compile::Schema->new('sample.xsd');
my $writer = $schema->compile(WRITER => 'TumorDetails');
my $doc = XML::LibXML::Document->new(q(1.0), q(UTF-8));

print $writer->($doc, $node)->toString;