Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I change xml structure

Status
Not open for further replies.

shlomyb

Programmer
Nov 14, 2006
32
IL
Hi
I have this xml file
<candy><product>Mints</product><product>Chocolate</product><product>Circus Peanuts</product></candy>

and I want it to be :

<candy>
<product>Mints</product>
<product>Chocolate</product>
<product>Circus Peanuts</product>
</candy>

HOW CAN I DO THAT ?
I am using XML::DOM::parser in my code ..
 
ask for it to find every <candy><product> and replace with <candy>\n\t<product>

Then ask for it to replace every <product></product> with <product>\n\t</product>

and finally ask for it to replace every </product></candy> with </product>\n</candy>

Just remember to escape the backslashes and you'll be set.
 
Hi

The following code reads your xml file and write it again using the same name. Save this code as xmlripout.pl as example. Save a copy of your xml file in the same directory where you have saved the perl script.

Then run it as:

perl xmlripout.pl yourxmlfile


Code:
$file =$ARGV[0];
$/=undef;
open FH, "<$file";
$xmlfile=<FH>;
close FH;
$xmlfile=~ s/\></\>\n</g;
open FH, ">$file";
print FH "$xmlfile";
close FH;


dmazzini
GSM System and Telecomm Consultant

 
Thats not much of an XML file, but if it's just like that and not a more complicated structure then you can use the solutions provided. Otherwise you might want to look into using one of the XML modules. XML::Simple might work.

- Kevin, perl coder unexceptional!
 
How about XML-Tidy?
Code:
use XML::Tidy;
my $xml_string = '<candy><product>Mints</product><product>Chocolate</product><product>Circus Peanuts</product></candy>';

my $xt = XML::Tidy->new('xml', $xml_string);
$xt->tidy("\t");

print $xt->toString();

Which gives you:
Code:
<?xml version="1.0" encoding="utf-8"?>
<candy>
        <product>Mints</product>
        <product>Chocolate</product>
        <product>Circus Peanuts</product>
</candy>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top