2011-02-17 85 views

回答

3

总而言之一句话,你需要做的:

  1. 转换的XSD格式的Perl哈希结构
  2. 构造此哈希,填写数据
  3. 转换哈希以XML

包所需:

  • XML ::编译::架构
  • XML ::的libxml ::文件

下面的代码创建一个从XSD定义一个Perl结构。

use XML::Compile::Schema; 
use Data::Dumper; 

my $filename = $ARGV[0] || ""; 

if(!$filename){ 
warn "Please provide the WSDL definition file."; 
exit 10; 
} 

my $schema = XML::Compile::Schema->new($filename); 
my $hash; 

print Dumper $schema->template('PERL' => 'Application'); 

然后由该程序创建的Perl数据结构如下:

{ 
    MakeName => 
    { 
    UniqueID => "anything", 
    _ => "example", }, 

     MakeDetails => 
    { 
     Name => 
     { 
     UniqueID => "anything", 
     _ => "example", }, 
    }, 
    }; 

所以,你的工作将建立在你的程序相同结构的其余部分,填写的内容,如:

my $hash = { 
    MakeName => { 
     UniqueID => 'xxxx', 
     _ => 'Name of the Make', 
    }, 

    OtherFields => foo_bar_get_other_hash(), 
    }; 
.... 

## breathtaking moment, create the XML from this $hash 

my $schema = XML::Compile::Schema->new("/opt/data/your.xsd"); 

my $doc = XML::LibXML::Document->new(); 
my $writer = $schema->compile(WRITER => 'Application'); 

my $xml; 

## Create $xml in the memory based on the Schema and your $hash 
eval{ $xml = $writer->($doc, $hash);}; 

if([email protected]){ 
# Useful if the format is invalid against the Schema definition 
    # Or if there are other errors may occurs 
    $err_msg = [email protected]>{message}->toString(); 
return ("", $err_msg); 
} 

## If you want save this $xml to file, convert it to string format first 
$doc->setDocumentElement($xml); 
my $ori_content = $doc->toString(1); 
## Now $ori_content holds the full XML content.