我现在在 sax 中有不同的模块,如 Author.pm、BillingPeriod.pm、Offer.pm、PaymentMethod.pm 等,每当我点击结束元素标签时,我想创建模块的对象,它相当于元素值。
我怎样才能做到这一点?
例如,如果我通过 XML 文件和 sax 解析器命中的结束元素进行解析,那么它应该创建 Offer.pm 的对象,类似地,如果 sax 解析器命中的结束元素标记那么它应该创建 Author.pm 的对象
代码
XML:books.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2009 sp1 (http://www.altova.com)-->
<bks:books xsi:schemaLocation="urn:books Untitled1.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bks="urn:books">
<book id="String">
<author>String</author>
<authorFirstName>String</authorFirstName>
<authorLastName>String</authorLastName>
<title>String</title>
<titleNo>3</titleNo>
<genre>String</genre>
<offer>String</offer>
<pub_date>1967-08-13</pub_date>
<review>String</review>
<reviewsratings></reviewratings>
</book>
</bks:books>
萨克斯:perlsaxparsing.pl
#!usr/bin/perl -w
use XML::SAX::ParserFactory;
use MySaxHandler;
my $handler = MySaxHandler->new();
my $parser = XML::SAX::ParserFactory->parser(Handler => $handler);
$parser->parse_uri("books.xml")
例如在下面的示例中,假设 sax 正在击中Offer end element tag
,所以正在创建对象Offer.pm
我想创建模块对象,例如,Offer.pm
在这种情况下,当 sax 命中 Offer 元素标记的结束元素时。
package Offer;
use strict;
# This class depicts the product_offer details
sub new {
my $class = shift;
my $self = {
_objectId => shift,
_price => shift
};
bless $self, $class;
return $self;
}
# Returns the ObjectID
sub getObjectId {
my ($self) = @_;
return $self->{_objectId};
}
# Returns the Price
sub getprice {
my ($self) = @_;
return $self->{_price};
}
# Check for undefined values and build a insert mapping table
sub doPreInsetCheck() {
my ($self) = @_;
my %refTable;
if ( defined $self->getObjectId == 1 ) {
$refTable{'object_id'} = $self->getObjectId;
}
if ( defined $self->getprice == 1 ) {
$refTable{'fk2_price'} = $self->getprice;
}
return %refTable;
}
# Returns the SQL Statement
sub getSQLScript {
my $tableName = 'product_offer';
my ($self) = @_;
my $sqlOutput = "Insert into " . $tableName . "(";
my %refTable = $self->doPreInsetCheck();
my @colNames = keys %refTable;
my $ctr;
foreach ( $ctr = 0 ; $ctr < ( $#colNames + 1 ) ; $ctr++ ) {
$sqlOutput .= $colNames[$ctr];
if ( $ctr < $#colNames ) {
$sqlOutput .= ",";
}
}
$sqlOutput .= ") values (";
my @colVals = values %refTable;
foreach ( $ctr = 0 ; $ctr < ( $#colVals + 1 ) ; $ctr++ ) {
$sqlOutput .= $colVals[$ctr];
if ( $ctr < $#colVals ) {
$sqlOutput .= ",";
}
}
$sqlOutput .= ");";
return $sqlOutput;
}
1;
SAX 解析器处理程序模块:MySaxHander.pm
sub end_element {
my($self,$data) = @_;
print "\t Ending element:".$data->{Name}."\n";
my $obj = new Price("1","2","NL","ENUM","DESCRIPTION","2008-01-01 10:00:00","2009-01-01 10:00:00","2008-01-01 10:00:00","USER");
print $obj->getSQLScript."\n";
$in_books--;
}
问题:使用 SAX 解析 XML 文件时,如何创建与元素值等效的模块对象?