How to read and write XML in .Net
The .NET Framework XML classes are made available through various System Namespaces. The core classes are available in System.Xml namespace. XmlReader and XMLWriter are the two abstract classes at the core of .NET Framework XML classes. These two classes define the common functionality that all derived classes must support. XmlReader provides a fast, forward-only, read-only cursor for processing an XML document stream. XmlWriter provides an interface for producing XML document streams that conform to the W3C's XML 1.0 and Namespaces Recommendations. So, if you are writing code to read XML documents, use XmlReader, and to create XML documents, use XmlWriter.
- XmlTextReader (a class derived from XmlReader) supports reading XML documents from a text-based stream, while XmlTextWriter (a class derived from XmlWriter) allows writing XML documents to a text-based stream.
- XmlNodeReader (a class derived from XmlReader) supports reading XML documents as in-memory DOM tree , while XmlNodeWriter (a class derived from XmlWriter) allows writing XML documents as in-memory trees.
< CameraStore ID="Hunts-Camera-Store" >
<location >Malden, MA </location>
< inventory>
<Camera ID="Canon-Sure-Shot-Z155" >
<fstop> 4.8-11.7</ fstop>
<focallength >4-155mm zoom</ focallength >
<cost > $318 USD</cost >
</Camera>
< Camera ID="Olympus-mju-II" >
<fstop >4.8 </fstop>
< focallength>mm </focallength >
< cost> $178 USD</ cost>
</Camera >
</ inventory>
</CameraStore >
Here I will write a demo project with the sample Xml which has the following functions:
- Create object instance with the data from sample xml using XmlTextReader
- Save data of object instances to xml using XmlTextWriter
CameraStore Class is the demonstration of XML CameraStore element section:
Camera Class is the demonstration of XML Camera element section:
Here is the code implementation:
* Created By HOME
* User: BPLOVEGCY
* Date: 2007-6-14
* Time: 16:22
*
* http://bplovegcy.blogspot.com/
*
*/
using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text ;
using System.Collections;
namespace XMLTesting
{
/// <summary>
/// Description of CameraStore.
/// </summary>
public class CameraStore
{
public CameraStore(){}
string id;
string location;
List<Camera> cameraList;
public string ID
{
get { return id; }
set { id = value; }
}
public string Location
{
get { return location; }
set { location = value; }
}
public List<Camera > CameraList
{
get { return cameraList; }
set { cameraList = value; }
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.AppendLine( string .Format(@"id={0},location={1}" ,id,location));
foreach(Camera camera in cameraList)
{
builder.AppendLine(camera.ToString());
}
return builder.ToString();
}
/// <summary>
/// Assume the file full path has valid format
/// </summary>
/// <param name="fileFullPath"></param>
public void ToXmlFile( string fileFullPath)
{
if(fileFullPath == null || fileFullPath == string.Empty )
throw new ArgumentNullException();
XmlTextWriter xmlWriter = new XmlTextWriter(fileFullPath, System.Text.Encoding.Unicode);
// show xml declaration <?xml version="1.0" encoding="utf-16"?>
xmlWriter.WriteStartDocument();
// <CameraStore>
xmlWriter.WriteStartElement(" CameraStore ");
xmlWriter.WriteAttributeString(" ID ",id);
xmlWriter.WriteElementString(" location ",location);
// <inventory>
xmlWriter.WriteStartElement( "inventory ");
foreach (Camera camera in cameraList)
{
camera.ToXml(xmlWriter);
}
// </inventory>
xmlWriter.WriteEndElement();
//</CameraStore>
xmlWriter.WriteEndElement();
// corresponding the xml declaration
xmlWriter.WriteEndDocument();
// save the content to file
xmlWriter.Close ();
}
/// <summary>
/// Assume the file full path has valid format
/// </summary>
/// <param name="fileFullPath"></param>
/// <returns></returns>
public static CameraStore ParseFromXML(string fileFullPath)
{
try
{
CameraStore store = new CameraStore();
if(! File.Exists(fileFullPath))
throw new ArgumentException(" The file doesn't exist!" );
System.Xml.XmlTextReader xmlReader
= new XmlTextReader(fileFullPath);
while(xmlReader.Read ()){
if (xmlReader.NodeType == XmlNodeType.Element){
switch (xmlReader.Name)
{
case " CameraStore ":
if (xmlReader.HasAttributes){
if(xmlReader.MoveToAttribute( "ID ")) store.id = xmlReader.Value;
}
break ;
case " location ":
store.location = xmlReader.ReadString();
break;
case "inventory ":
store.cameraList = Camera.ParseFromXML(xmlReader);
break ;
}
}
}
return store;
} catch(Exception ex){
throw ex;
}
}
}
public class Camera
{
string id;
string fstop;
string focallength;
string cost;
public Camera(){}
public string ID
{
get { return id; }
set { id = value; }
}
public string Fstop
{
get { return fstop; }
set { fstop = value; }
}
public string Focallength
{
get { return focallength; }
set { focallength = value; }
}
public string Cost
{
get { return cost; }
set { cost = value; }
}
public override string ToString()
{
return string.Format("id={0},fstop={1},focallength={2},cost={3} ",
id,fstop,focallength,cost);
}
public static List< Camera > ParseFromXML(XmlTextReader xmlReader)
{
List< Camera > cameraList = new List<Camera> ();
Camera camera = null;
while(xmlReader.Read()){
if(xmlReader.NodeType == XmlNodeType.Element){
switch (xmlReader.Name)
{
case " Camera ":
camera = new Camera();
// get the attribute id
if (xmlReader.HasAttributes && xmlReader.MoveToAttribute(" ID" )){
camera.id = xmlReader.Value;
}
break;
case "fstop ":
// here to get a element value use the read string
// get attribute value first move to the attribute then get the value
camera.fstop = xmlReader.ReadString();
break;
case "focallength":
camera.focallength = xmlReader.ReadString();
break;
case "cost " :
camera.cost = xmlReader.ReadString();
break;
default:
// nothing just move next
break;
}
} else if( xmlReader.NodeType == XmlNodeType.EndElement
&& xmlReader.Name == "Camera")
if( camera != null ) cameraList.Add(camera);
}
return cameraList;
}
public void ToXml(XmlTextWriter xmlWriter)
{
if(xmlWriter == null )
throw new ArgumentNullException();
xmlWriter.WriteStartElement("Camera" );
xmlWriter.WriteAttributeString("ID" ,id);
xmlWriter.WriteElementString("fstop" ,fstop);
xmlWriter.WriteElementString("focallength" ,focallength);
xmlWriter.WriteElementString("cost ",cost);
//</Camera>
xmlWriter.WriteEndElement();
}
}
}
Here is the testing code (NUnit framework):
* Created By HOME
* User: BPLOVEGCY
* Date: 2007-6-14
* Time: 17:02
*
* http://bplovegcy.blogspot.com/
*
*/
using NUnit.Framework;
using System;
using System.Reflection ;
using System.IO;
using System.Resources;
namespace XMLTesting
{
[TestFixture]
public class Testing
{
[Test]
public void TestMethod()
{
// Please modify the path pointing to the location of the CameraStore.xml
string xmlFilePath = @" C:\CameraStore.xml";
CameraStore store = CameraStore.ParseFromXML(xmlFilePath);
Console.WriteLine(store.ToString());
const string FilePath = "c:\\testing.xml";
store.ToXmlFile (FilePath);
}
}
}
--
Happy day, happy life!
























































































