sureerat has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I'm studying more about XML::Twig. It can parse hash into XML easily .. However, I have question whether there's the same way to parse the data from hash to XML if some values are attribute.

Now I use this method:

  1. hash only the node that has no attribute
  2. manually create new node and set attribute then paste to the parent one by one
This is my current coding:
use XML::Twig; my %links = ( section => "Computer", title => "PerlMonks", ); $id = "B0001"; $url = "http://www.perlmonks.org"; $target = "_blank"; my $clink = XML::Twig::Elt->new( record => map { XML::Twig::Elt->new( $_ => $links{$_}) } sort keys %links) ->set_att("id",$id); my $curl = XML::Twig::Elt->new(url => $url) ->set_att("target",$target); $curl->paste('last_child',$clink); my $twig = XML::Twig->new(pretty_print => 'indented'); $twig->set_root( XML::Twig::Elt->new(data => $clink) ); $twig->print;
This is the output:
<data> <record id="B0001"> <section>Computer</section> <title>PerlMonks</title> <url target="_blank">http://www.perlmonks.org</url> </record> </data>
Thank you in advance for all help.

Replies are listed 'Best First'.
Re: Hash to XML with XML::Twig
by Jenda (Abbot) on Dec 02, 2008 at 14:45 UTC

    Does it have to be XML::Twig?

    use XML::Rules; my $parser = XML::Rules->new( rules => {}, ); print $parser->ToXML( data => { record => { id => 'B0001', section => [ 'Computer' ], title => [ 'PerlMonks' ], url => { target => '_blank', _content => 'http://www.perlmonks.org', } } }, 0, ' ', );

    The unnamed arrays are there to make sure the section and title produce tags and not attributes. Another option would be to use section => {_content => 'Computer'}.

      Hello Jenda,

      Thank you for your reply. XML::Rules is new for me but from your example, it is an easier way to handle my task. It's interesting. I will read more about it. However, just doubt whether XML::Twig can't do the similar way.