How to find a word and move it a specific location in xml file using perl?

Hi friends,

I have one XML file having below structure :-

INput XML file :-
<?xml version="1.0" encoding="UTF-8"?>
<START> 
<A=value1>
<attr name1="a1">
</A>
<B=value2>
<attr name2="b1">
<attr name3="c1">
</B>
</START>
 

output xml file should be

<?xml version="1.0" encoding="UTF-8"?>
<START> 
<A=value1>
<attr name1="a1">
<attr name2="b1">
<attr name3="c1">
</A>
</START>
 

Can anybody please help me. I am having little knowledge of perl.
I just know how to open file and read it :-

open xmlsource, "$filename";
undef $/;#slurp
$myfile = <xmlsource>;
close xmlsource;
chomp $myfile;
print $myfile;

Must you update the file in place, or can we make a copy? Is the word moving to a equally legal place in the xml schema? Within a file, move upward is copy source word to memory, rewrite file between target and source sliding the data down, then write the source word. For a copy, you need to copy the earlier file part first and the later file part last. For downward, you need to buffer input whose file space is being overwritten into two buffers, write the word, the first buffer, reload the first buffer, write the second buffer, reload the second buffer, etc. through the middle. You might copy the word to move and the middle data into memory and then rewrite it all with the word moved, if it will fit. I'd feel safer making a new file. Disk is cheap.

1 Like

Thanks a lot for replying DGPickett.

In my case i need to changed input xml file and then move it to other location.

Here copy of input file is not allowed.

In input file <attr name1="a1"> is fixed always and <attr name2="b1"> and <attr name3="c1"> should come after <attr name1="a1"> only.

If i execute script on input.xml file then after everything is done ..all changes should reflect in same input.xml file.

Can we do something like open xml file then use find and replace and remove whatever is extra..But as i dont have idea about perl..i dont know how to do it...

Once again thanks for you time :slight_smile:

There are PERL tutorials on the web that are a fine use of your time, and I am told it is the most versatile tool of all, being midway between c/C++/JAVA and shell/sed/awk. Learning it is a big task for a newcomer to computers, but learning your first language and O/S language interface is a big task regardless.

A tool like sed or sed-like-perl can copy the file, capturing lines (sed h, d) it finds by context (sed /pattern/ and N) and moving them (sed G) to new places it finds by context. LINUX Man Pages and LINUX Commands at the UNIX and Linux Forums

However, the only really robust way to adjust an XML file is to use or create an XML-aware tool. PERL/C++/JAVA have XML parsers that will put the document in memory as a container object (DOM). Once there, you can adjust the content and write a new XML file.