Home » C# ProgrammingRSS

How to add New XML Tags to an Existing XML File

Hi,

I have an xml file with this format:

<?xml version="1.0"?>

<FutDates Type="Secs">

<Secs Cur="1T" Sec="1A" FutDate="1Month"/>

</FutDates>.

 

Please let me know how can i programatically add another Secs Tag to the existing file, which would look like this

<Secs Cur="1T" Sec="1A" FutDate="1Month"/>

<Secs Cur="2T" Sec="2A" FutDate="2Month"/>

 

With Regards

Li2

 

 

 

3 Answers Found

 

Answer 1

FileStream fs = new FileStream("foo.xml", FileMode.Open);
XmlSerializer ser = new XmlSerializer(typeof(FutDates));
FutDates futDates = (FutDates)ser.Deserialize(fs);

futDates.Secs.Add(new Sec() { Cur="2T" });

TextWriter writer = new StreamWriter("newfoo.xml");
ser.Serialize(futDates, writer);
writer.Close();

You need to deserialize the xml  file into a FutDates collection, add  another Secs instante to that collection and serialize it once again.

Do you already have the FutDates and Secs classes with the serialization attributes?

 

It would be something like:

publicclass FutDates {
 [XmlAttribute]
 publicstring Type { get; set; }
 [XmlArray]
 public List<Sec> Secs { get; set; }
}

publicclass Sec {
 [XmlAttribute]
 publicstring Cur { get; set; }
 [XmlAttribute]
 publicstring Sec { get; set; }
 [XmlAttribute]
 publicstring FutDate { get; set; }
}

The  code to deserialize, create a new item and serialize again would look something like:

FileStream fs = new FileStream("foo.xml", FileMode.Open);
XmlSerializer ser = new XmlSerializer(typeof(FutDates));
FutDates fut = (FutDates)ser.Deserialize(fs);

fut.Secs.Add(new Sec() { Cur = "2T" });

TextWriter writer = StreamWriter("newfoo.xml");
ser.Serialize(writer, fut);
writer.Close();
Note that I haven't tested this code against a compiler, so it could have errors
 

Answer 2

If you have .Net 3.5, you can use the XDocument class.

XDocument doc = XDocument.Load("test.xml");
doc.Element("FutDates").Add(
  new XElement("Secs",
    new XAttribute("Cur", "2T"),
    new XAttribute("Sec", "2A"),
    new XAttribute("FutDate", "2Month")
  )
);
doc.Save("test.xml");
 

Answer 3

Hi litu,

Welcome to MSDN forums!

@Louis is a good solution to your question. If your question has been solved, please don’t forget mark/vote the replies which helped you, and this will encourage the other community members to join in discussion and help each one.

Have a nice day!

Alan Chen

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter