views:

75

answers:

3

I'm filling an XML document manually using C# and I need to have <data> as header and </data> as footer for the whole XML file. Is there an easy way to do that ? I know It can be done but I couldn't find a way to do it. Keep in mind that I'm updating the entries so I need to make sure that they always come between the header and the footer.

Thanks

Example

<data>

Entry
New Entry 1
New Entry 2

</data>
+4  A: 

As for appending text to a file, this is easy just open the file in append mode and write the text.

For inserting, there is no POSIX or Windows way available to insert text. So you need to write a new file with the header, and then write the rest of the file.

Brian R. Bondy
just being completely hypothetical, but on a low level, could you write a hard disk sector and change the file system pointer to that new sector as the beginning of a file? Obviously such a weird approach would only make sense for huuge files
flq
@Frank: I think you'd have to deal with the MFT of the disk. Which I wouldn't advise to do :)
Brian R. Bondy
+2  A: 

I'm not sure what you are trying to do makes sense - and I agree with Brian on a lack of way to pre-pend a file without writing a new file. A better approach would be to store the Entry items (in a separate file or other storage medium) and then generate the final version as Brian stipulates.

If you are manipulating XML content generally, you might consider using Linq to XML or the native .Net XML libraries.

AJ
A: 

Well, simplest is to use these three commands in the following order. Of course, this doesn't take care of checking if you already put the tags or not. For that, you should use XML related libs.

Assume, file is ab.txt. Run these dos commands -

echo ^<data^> > new_ab.txt
type ab.txt >> new_ab.txt
echo ^<^/data^> >> new_ab.txt

:)

There are many ways to do it. Do you want to do it via C# code? It will be bit lengthy to put it here :) I'm sure you know how to read/write files via C#.

Cheers!

Assumption: you are working on Windows. For unix, commands are much easier. :)

Nayan
Input file: ab.txt, output file: new_ab.txt
Nayan