Jump to content

Writing in the middle of a xml file?


umairmasood

Recommended Posts

I have a file named example.xml

 

I want to know how to write to the 3rd line on this file? What function to use?

 

I want to be able to write to this xml file right after the <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> tag.

 

Please someone tell me how?

 

Much appreciated.

 


<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <sitemap>
      <loc>http://www.example.com/sitemap1.xml.gz</loc>
      <lastmod>2004-10-01T18:23:17+00:00</lastmod>
   </sitemap>
   <sitemap>
      <loc>http://www.example.com/sitemap2.xml.gz</loc>
      <lastmod>2005-01-01</lastmod>
   </sitemap>
</sitemapindex>

Link to comment
Share on other sites

There is no way to directly insert data into a file.  Instead you need to write the extra lines you want and then write ALL the following data back to the file again.  The simplest would be to read the entire file into an array, one item per line, then add the extra lines and write it all back.

 

You could also parse the xml, edit the resulting structure and rewrite it, but that can be tricky to get right.

Link to comment
Share on other sites

thanks for your response...

 

So there is no easy way to this?

 

I would have tried the simplest way you mentioned (using an array) but my xml file is supposed to have more than 50,000 lines at least. So this is hugely strain the server.

 

So can you please confirm if there is no other way of achieving this other than the 2 methods you have proposed?

 

Thanks.

Link to comment
Share on other sites

If the file is large, you could take an approach like this:

 

1.  Read the first few lines, write them into a new file

2.  Add your extra lines into the new file

3.  Read the rest of the lines from the original file, write them into the new file

4.  Replace the old file with the new file.

 

That's about the best I can think of.  If you do it that way, line by line, then you will have no memory issues when dealing with a large file.  You do have to read every line, but there's no way around that if you're inserting text.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.