What do you think I should do?
I think you shouldn't use XML::Simple! There are lots of issues with that module, especially with writing XML. There are several much better modules for XML handling, such as XML::Rules (which can often replace XML::Simple for reading XML) or XML::Twig, but for writing XML, personally I like to use XML::LibXML because it gives me the most control. (Update: Note the following makes some assumptions about the input data format, such as that you don't have any arrayrefs, as well as the output format, because the sample data you've provided is pretty short, and you haven't explained what rules should be used for conversion. But I hope it's a starting point.)
use warnings; use strict; use XML::LibXML; my $hash = { 'root' => { 'item1' => { 'item1a' => 'n1', 'item1b'=>'jh' } } }; my $dom = XML::LibXML::Document->createDocument(); # recursively convert hashes to elements my $frag = $dom->createDocumentFragment(); my $hash2el; $hash2el = sub { my ($n,$h) = @_; for my $key (sort keys %$h) { my $el = $dom->createElement($key); if (ref $h->{$key} eq 'HASH') { $hash2el->($el, $h->{$key}) } else { $el->appendText( ''.$h->{$key} ) } $n->appendChild($el); } }; $hash2el->($frag, $hash); # either a single root node, or multiple nodes in a new root my @roots = $frag->nonBlankChildNodes(); if (@roots==1) { $dom->setDocumentElement( $roots[0] ); } elsif (@roots>1) { my $root = $dom->createElement('root'); $root->appendChild($frag); $dom->setDocumentElement( $root ); } print $dom->toString(1); __END__ <?xml version="1.0"?> <root> <item1> <item1a>n1</item1a> <item1b>jh</item1b> </item1> </root>
In reply to Re: XMLOut in XML::Simple returning unwanted xml format
by haukex
in thread XMLOut in XML::Simple returning unwanted xml format
by perl_help27
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |