1

I am quite new to XML. I have an XML file which contains around 8000 products and I will import these products into my own system. I want to modify this XML file for my importer. Sample product on original XML file is below;

  <product prodID="PD42BJ1000002020" prodName="Intermec PD42" prodBrand="INTERMEC" globProdID="PD42BJ1000002020">
    <tax>KDV18</tax>
    <pic>http://.....jpg</pic>
    <prodSpec>
      <prd spec="Connectivity Interfaces" DEGER="USB - Serial RS232 - Ethernet"/>
      <prd spec="Print Width" DEGER="104"/>
      <prd spec="Printing Method" DEGER="Direct Thermal - Thermal Transfer"/>
      <prd spec="Resolution (DPI)" DEGER="203"/>
    </prodSpec>
  </product>

I want to change product specs to unique elements like below;

  <product prodID="PD42BJ1000002020" prodName="Intermec PD42" prodBrand="INTERMEC" globProdID="PD42BJ1000002020">
    <tax>KDV18</tax>
    <pic>http://.....jpg</pic>
      <pr001>Connectivity Interfaces:USB - Serial RS232 - Ethernet</pr001>
      <pr002>Print Width:104</pr002>
      <pr003>Printing Method:Direct Thermal - Thermal Transfer</pr003>
      <pr004>Resolution (DPI):203</pr004>
  </product>

Is it possible to change whole XML document like that?

3
  • Can you provvide us any clue on the technologie(s) you must use or not (XSLT, pure programming language, ...) ? Commented Feb 24, 2015 at 8:32
  • Hey, thank you for answering! I am going to import XML using PHP to MySQL database. The PHP code that requires is different attribute sets like <atr></attr> instead of <attr <at1 x="" y=""/> </attr>. I am quite new to XML so I don't know about XSLT :/ Commented Feb 24, 2015 at 9:07
  • 1
    I don't know PHP so I can't help you further. But there do exist some libraries to handle XML -- I believe you can find something useful here on stackoverflow : stackoverflow.com/questions/tagged/xml+php Commented Feb 24, 2015 at 10:58

1 Answer 1

2

If you don't mind using Perl for this, here is a way to do it using XML::Twig:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $infile= shift @ARGV;

XML::Twig->new( twig_handlers => { prodSpec => \&tweak_product },
                pretty_print => 'indented',
              )
          ->parsefile( $infile);

exit;

sub tweak_product
  { my( $t, $prodspec)= @_;
    my $i=0;                                       # sub tag number 
    foreach my $prd ($prodspec->children( 'prd'))  
      { my $tag= sprintf( 'pr%03d', ++$i);
        $prd->set_tag( $tag)
            ->set_text( $prd->att( 'spec') . ':' . $prd->att( 'DEGER'))
            ->del_atts;
      }
    $prodspec->erase;
    $t->flush;
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.