Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input XML data doen't match with the output XML format

Tags:

xml

perl

Input XML

<?xml version="1.0" encoding="utf-8"?>
<!--00/00/0000 12:35:25 AM-->
<Physical xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
  <Pro managementID="22000020">
    <Identification Type="XXXXX" >          
      <Address>
        <Data>test</Data>        
      </Address>
      <Phone>
        <Number>0000</Number>
      </Phone>
      <Email>test@com</Email>
    </Identification>       
  </Pro>
</Physical>

Script:

I am trying to change the value of the tag and print the rest to a new output xml file

use strict;
use warnings;
use XML::Simple;
use Data::Dumper;     

  my $xml = XML::Simple->new(ForceContent => 1,);
  my $xmlData = $xml->XMLin('input.xml') or die$!;     

  print Dumper (\$xmlData);

  foreach my $xmlKey ( keys %{$xmlData} ){
   if ( $xmlKey =~ m/Pro/){
       print ${$xmlData}{$xmlKey}{Identification}{Address}{Data}="hello";
    }
  }

XMLout(
    $xmlData,
    KeepRoot => 1,
    NoAttr => 0,
    OutputFile => $xml_out,
);

Outout XML:

<opt xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Pro managementID="22000020">
     <Identification Type="XXXXX">
      <Address Data="hello" />
      <Email>test@com</Email>
      <Phone name="Number">0000</Phone>
    </Identification>
  </Pro>
</opt>

I am able to change the value, but whem i am trying to write the data to the ouput the format has been changed.Can any one guide me to get the same input data with changed value as output.

like image 403
Anil Avatar asked Nov 23 '25 07:11

Anil


1 Answers

use XML::LibXML this way:

#!/usr/bin/perl
use strict;
use warnings;

use XML::LibXML;

my $input;
while(<>) {
    $input .= $_;
}
my $xml_doc = XML::LibXML->load_xml(string => $input);
my $xpath_ctx = new XML::LibXML::XPathContext($xml_doc);
$xpath_ctx->find("/Physical/Pro/Identification/Address/Data")->get_node(0)->firstChild()->setData("hello");
my $xml_data = $xpath_ctx->find("/")->get_node(0)->toString(1);

print $xml_data;

XML::LibXML is much faster and with the help of the XPath, the manipulation of the $xml_doc is much easier.

more infos you can find here

like image 159
Memos Electron Avatar answered Nov 24 '25 21:11

Memos Electron