2011-02-17 118 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.