in reply to XMLOut in XML::Simple returning unwanted xml format

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>

Replies are listed 'Best First'.
Re^2: XMLOut in XML::Simple returning unwanted xml format
by perl_help27 (Acolyte) on May 22, 2018 at 18:40 UTC
    Maybe I can use that for more complicated situations. Thank you for the insight I will keep it in mind

      You should get used to reading documentation, the first line of the module synopsis:

      PLEASE DO NOT USE THIS MODULE IN NEW CODE.

        Yeah, And if you read the pod for threads it reads "The use of interpreter-based threads in perl is officially discouraged.".

        Probably contributed by the same ass.


        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
        In the absence of evidence, opinion is indistinguishable from prejudice. Suck that fhit