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

Hi Monks!! I need to write attribute key value pair dynamically in XML file using XML::Writer package. I tried to do this by concatenating multiple string in array as:

$self->xml->startTag("Contact", "Type"=>"Information", "Phone"=>$cContactPhone, "Email"=>$cContactEmail);
But not able to write in correct way, its showing result as:
<Contact Type = "Information"="Phone = +13824898944" Email = "abctest@ +abc.com"="">I am here to ask questions</Contact>
Can anyone please advise for any alternate way to write this logic dynamically.

Replies are listed 'Best First'.
Re: XML::Write challenges
by poj (Abbot) on Feb 04, 2019 at 08:24 UTC

    You need to post a complete SSCCE because this works for me.

    #!/usr/bin/perl use strict; use XML::Writer; printf "OS=%s Perl=%s XML::Writer=%s\n",$^O,$^V,$XML::Writer::VERSION; my $writer = XML::Writer->new(); my $cContactPhone = 13824898944; my $cContactEmail = 'abctest@abc.com'; $writer->startTag("Contact", "Type" => "Information", "Phone" => $cContactPhone, "Email" => $cContactEmail ); $writer->characters('I am here to ask questions'); $writer->endTag("Contact");

    output:

    OS=MSWin32 Perl=v5.16.1 XML::Writer=0.625
    <Contact Type="Information" Phone="13824898944" Email="abctest@abc.com">I am here to ask questions</Contact>
    
    poj

      Hi Poj, Thanks
      but it looks like I was not clear in my question.
      I need to print the both attribute key and value dynamically via XML:Writer. e.g. if $cContactPhone value is blank then the XML should be printed as below.

      <Contact Type="Information" Email="abctest@abc.com" Contact Name ="I a +m here to ask questions"</Contact>
      if $cContactEmail value is blank then it should print as below
      <Contact Type="Information" Phone="13824898944" Contact Name ="I am he +re to ask questions"</Contact>
      Thanks

        If you don't want something to appear in the output, don't tell the module to output it. Basically
        $attributes{"Type"} = $information if $information; $attributes{"Phone"} = $cContactPhone if $cContactPhone; $attributes{"Email"} = $cContactEmail if $cContactEmail; $self->xml->startTag("Contact", %attributes);

        Edit:
        Typo


        holli

        You can lead your users to water, but alas, you cannot drown them.

        If you have many attributes then consider map and grep

        #!/usr/bin/perl use strict; use XML::Writer; my $writer = XML::Writer->new(); my %obj = ( Type => 'Information', Phone => 0, Email => '', ); my %attr = map { $_ => $obj{$_} } grep { length $obj{$_} } keys %obj; $writer->startTag("Contact",%attr);
        poj