任何人都可以請我演示一個使用XML::Compile::Schema從XSD生成XML的示例。使用XML從XSD生成XML的示例Perl代碼::編譯
我想發佈我的腳本,我試圖與XSD一起,但我無法做到這一點。所以我正在尋找一個示例。
任何人都可以請我演示一個使用XML::Compile::Schema從XSD生成XML的示例。使用XML從XSD生成XML的示例Perl代碼::編譯
我想發佈我的腳本,我試圖與XSD一起,但我無法做到這一點。所以我正在尋找一個示例。
總而言之一句話,你需要做的:
包所需:
下面的代碼創建一個從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.