Reading/Writing XML files

1.  XmlWriter – This is simple but tedious and error prone.  You can create an XmlWriter and use WriteStartElement, WriteElementString, and WriteEndElement to explictly write the XML statements.

If writing to a file, set the XmlWriterSettings.Indent property to true.  Otherwise you don’t get any indents or carriage returns in the output file.

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
writer = XmlWriter.Create(m_Document,settings);

2.  XmlTextWriter – MSDN recommends using XmlWriter rather than XmlTextWriter in .Net 2.0

2.  XmlDocument – You can create “Chunks” of the XML file independently.

 3.  XmlSerializer – Automatically writes the public fields/properties to a file.

private void writeUsingXmlTextWriter() { System.Xml.XmlTextWriter xWriter = new System.Xml.XmlTextWriter(filepath,Encoding.Default); xWriter.WriteStartDocument(); xWriter.WriteStartElement("Views"); foreach (CustomView view in viewList) { xWriter.WriteStartElement("View"); xWriter.WriteElementString("Name", view.Name); xWriter.WriteElementString("EventTime", view.eventTime.ToString()); xWriter.WriteElementString("TimeSpan", view.totalTimeSpan.ToString()); xWriter.WriteEndElement(); } xWriter.WriteEndElement(); xWriter.Close(); } private void writeUsingXmlSerializer() { System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(view1.GetType()); System.IO.StreamWriter sw = new System.IO.StreamWriter(filepath); writer.Serialize(sw, viewList[0]); //foreach(CustomView view in viewList) //{ // writer.Serialize(sw, view); //} sw.Close(); } private void writeUsingXmlDocument() { // TODO: Replace xElement with xNode System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); System.Xml.XmlNode xElement = xDoc.CreateElement("Views"); System.Xml.XmlNode xChild = xDoc.AppendChild(xElement); foreach(CustomView view in viewList) { xChild.AppendChild(view.ToXml(xDoc)); } System.Xml.XmlWriter xWrite = System.Xml.XmlWriter.Create(filepath); xDoc.WriteContentTo(xWrite); xWrite.Close();   } private void readUsingXmlDocument() { System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.Load(filepath); System.Xml.XmlNodeList xNodes = xDoc.GetElementsByTagName("View"); foreach (System.Xml.XmlNode xNode in xNodes) { CustomView view = new CustomView(xNode); Console.WriteLine("{0} {1} {2}", view.Name, view.eventTime, view.totalTimeSpan); } }

Post a Comment

Required fields are marked *

%d bloggers like this: