Proper way to write a CLEAN xml file (erasing old data first)

D

darrel

I'm backtracking to a problem I had a month or so ago.

I need to write XML files quite a bit. I'm finding that the way I'm doing it
doesn't write a new, clean XML file each time, but just dumps the new data
'on top' of the old stuff.

If the new data is shorter than the old data, the remainder of the old data
just sits at the end of the file making the XML file invalid.

Example:

if my existing data is:

<items>
<item></item>
<item></item>
</items>

and my new data is:

<items>
<item></item>
</items>

What gets written is:

<items>
<item></item>
</items>
</items>

I'm writing the XML using this:

Dim fs As New System.IO.FileStream("myfile.xml"), IO.FileMode.Open,
IO.FileAccess.Write, IO.FileShare.Read)
objXMLWriter = New System.xml.XmlTextWriter(fs,
System.Text.Encoding.Default)

Should I be using something else? XMLWriter? Textwriter?

Up to now, the 'fix' I've been using is to first delete the XML file. Create
a new streamwriter, output it to a blank text file with the 'myfile.xml'
name, and then doing the xml writer. But this seems like a hack. I'm
guessing there is some method I should be using that will first delete the
content of the xml file before writing the new content automatically.

-Darrel
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Use IO.FileMode.Create to truncate the file if it exists.
 
D

darrel

Use IO.FileMode.Create to truncate the file if it exists.

Is there an advantage to that vs. just deleting and creating a new blank
file?

I find it odd that, by default, xmlWriter doesn't first clear the file
before writing...seems to be standard practice for every application I've
ever used. ;o)

-Darrel
 
D

darrel

Use IO.FileMode.Create to truncate the file if it exists.
Is there an advantage to that vs. just deleting and creating a new blank
file?

Oh. Duh! Nevermind!

Yea, I was OPENING a file rather than CREATING it. Thanks!

-Darrel
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

darrel said:
Is there an advantage to that vs. just deleting and creating a new blank
file?

Less code.
I find it odd that, by default, xmlWriter doesn't first clear the file
before writing...seems to be standard practice for every application I've
ever used. ;o)

Not odd at all. You specifically opened the stream for writing with the
current content intact. The XmlWriter just writes to the stream that you
supply to it.

If you would have used the XmlWriter.Create method to open the stream,
it would have used IO.FileMode.Create to open the file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top