DukeOfMarmalade
DukeOfMarmalade

Reputation: 2788

Add node and childnodes to XML File

I have an XML file like this:

<LogFiles>
<Type1>
<File>
  <Component>1</Component>
  <Path>C:\TypeFiles</Path>
  <FileName>a.txt</FileName>
</File>
<File>
  <Component>1</Component>
  <Path>C:\TypeFiles</Path>
  <FileName>b.txt</FileName>
</File>
</Type1>
<Type2>
<File>
  <Component>2</Component>
  <Path>C:\TypeFiles2</Path>
  <FileName>c.txt</FileName>
</File>
</Type2>
</LogFiles>

I want to be able to add file nodes from my C# code. I have looked at XML Serializer but it seems to mean creating an object to hold file details and so a lot of redesign of my application. Some of the other XML Writer ways I have looked at seem to wipe everything in the XML file and then add the new file node, which is not what I want. Any ideas would be a huge help.

Upvotes: 0

Views: 431

Answers (1)

7heViking
7heViking

Reputation: 7577

Well I have always used the XmlSerializer. I I want to write it to the file I would to like this:

XmlSerializer serializer = new XmlSerializer(typeof(yourObject));
TextWriter streamWriter = new StreamWriter(filename);
serializer.Serialize(streamWriter, yourObject);
streamWriter.Close();

It might be that you just can add the data one by one, but then you will loose the object orientation. If I was you I would reconsider making some changes to your application so you can use the XmlSerializer.

Upvotes: 1

Related Questions