Attaching tags or multiple tags in XML :: COMPILE :: SCHEMA
I gave xsd file, Perl Enviroment and can only use XML::LibXML , XML::SAX, XML::Compile
The relevant part from the xsd is
<complexType name="property">
<attribute type="propertyvalue" name="name" use="required"/>
<attribute type="string" name="value" use="required"/>
</complexType>
<simpleType name="propertyvalue">
<restriction base="string">
<enumeration value="propertya"/>
<enumeration value="propertyb"/>
[....some more values...]
</restriction>
</simpleType>
I need to write multiple properties for each value. So far I've worked with XML :: Compile :: Schema
$schema->template('PERL', $type);
my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
my $write = $schema->compile(WRITER => $type, use_default_namespace => 1);
my %hash;
$hash = {
properties =>
{
version => 42,
property =>
[ {name => "propertya",
value => "example",
}, ],
}
};
my $xml= $write->($doc, $hash);
$doc->setDocumentElement($xml);
My problem so far, I can't see a way how I can add multiple property tags with something like
@properties =("propertya","propertyb",[.and so on.]);
foreach my $pname (@properties){
$hash = {
properties =>
{
version => 42,
property =>
[ {name => $pname;
value => "example",
}, ],
}
};
my $xml= $write->($doc, $hash);
$doc->setDocumentElement($xml);
}
without overwriting everything or getting messages that are missing in other parts of the file. Is there a way to do this and is there a way to attach tags later after doing my $xml = $write->($doc, $hash);
source to share
The property value in your hash is just a reference to an anonymous array / array. This way you can simply process your properties in name value pairs in a foreach loop and cast them to an array. Then you only need to create the hash of the hash once and give it a reference to the props array you created in your foreach loop.
use strict;
use warnings;
use Data::Dumper;
my @properties=("propertya","propertyb","propertyc");
my @props;
foreach my $pname (@properties){
push(@props, {name=>$pname, value=>'example'});
}
my $hash = {
properties =>
{
version => 42,
property => \@props
}
};
print Dumper $hash
as you can see the property now has an array of properties.
$VAR1 = {
'properties' => {
'version' => 42,
'property' => [
{
'value' => 'example',
'name' => 'propertya'
},
{
'value' => 'example',
'name' => 'propertyb'
},
{
'value' => 'example',
'name' => 'propertyc'
}
]
}
};
source to share