有人可以给我看一个使用XML::Compile::Schema从XSD生成XML的示例。
我正在尝试发布我正在尝试使用XSD的脚本,但我无法做到这一点。所以我正在寻找任何一个示例。
答案 0 :(得分:3)
我刚刚写了一篇关于这个的教程:http://blogs.perl.org/users/brian_e_lozier/2011/10/using-xmlcompile-to-output-xsd-compliant-xml.html
答案 1 :(得分:3)
简而言之,您需要这样做:
所需的套餐:
以下代码从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.