示例使用XML :: Compile从XSD生成XML的Perl代码

时间:2011-02-17 14:28:09

标签: perl xsd

有人可以给我看一个使用XML::Compile::Schema从XSD生成XML的示例。

我正在尝试发布我正在尝试使用XSD的脚本,但我无法做到这一点。所以我正在寻找任何一个示例。

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:3)

简而言之,您需要这样做:

  1. 将XSD格式转换为Perl哈希结构
  2. 构建此哈希,填写数据
  3. 将哈希转换为XML
  4. 所需的套餐:

    • XML :: Compile :: Schema
    • 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($@){
    # Useful if the format is invalid against the Schema definition
        # Or if there are other errors may occurs
        $err_msg = $@->{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.