|
Posted by mirod on March 20, 2008, 6:40 am
Please log in for more thread options
> there are some modules aimed to make the xml generation easy - =A0
> XML::Generator, XML::Writer and XML:Writer::Simple, for example.
>
> For my needs, these are to "verbose" and there is too much code necessary
> to express the structure of the resulting xml. So I wrote a piece of code
> which uses a bit more declarative approach. If somebody finds it useful,
> I'd put it on CPAN - or submit it to an existing module.
>
> Let's look at this code:
>
> $str =3D element "outer", content {
> =A0 =A0 =A0 =A0 element "inner" =3D> content {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 attribute id =3D> 1;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 element "abc", undef;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 opt_element "def", $value;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 element "ghi", "bb & cc";
> =A0 =A0 =A0 =A0 }
>
> }
>
> provided that $value contains "dummy", $str contains the following result:=
>
> <outer>
> =A0 <inner id=3D'1'>
> =A0 =A0 <abc/>
> =A0 =A0 <def>dummy</def>
> =A0 =A0 <ghi>bb & cc</ghi>
> =A0 </inner>
> </outer>
>
> provided that $value is undef or "", $str would contain:
>
> <outer>
> =A0 <inner id=3D'1'>
> =A0 =A0 <abc/>
> =A0 =A0 <ghi>bb & cc</ghi>
> =A0 </inner>
> </outer>
>
> Another example:
>
> $str =3D opt_element "abc", content {
> =A0 =A0 =A0 =A0 opt_element "def", $value
>
> }
>
> provided $value is undef or "", as result, $str would contain "".
> If $value would be "zzz", $str would contain:
>
> <abc>
> =A0 <def>zzz</dev>
> </abc>
>
Have you looked at HTML::Element? It lets you create elements from a
Perl structure:
http://search.cpan.org/~petek/HTML-Tree-3.23/lib/HTML/Element.pm#@elements_=
=3D_HTML::Element-%3Enew_from_lol(ARRAYREFS)
Your first example would be:
my $elt =3D HTML::Element->new_from_lol(
[ outer =3D>
[ inner =3D> { id =3D> 1 },
[ 'abc' ],
$value && [ def =3D> $value ],
[ ghi =3D> 'bb & cc' ],
]
]);
print $elt->as_XML;
XML::TreeBuilder is based on HTML::Element and can be used to process
XML.
You could add a function opt_elt to avoid repeating the $value, and
you would be quite close to your original syntax, while getting the
rest of the XML::TreeBuilder fetures for free.
--
mirod
|