Friday, April 24, 2009

Don't use XmlDocument use XmlTextReader instead

I had an assignment to read a 200 MB xml file
i dont think that XmlDocument can help me here...
so i found the XmlTextReader object that made a great job
and from this moment i always use XmlTextReader to read
xml file content, so here is my example:

lets say that i want to read this Test.xml file:

<?xml version="1.0" encoding="utf-8" ?>



<Item Att="1">A</Item>

<Item Att="2">B</Item>



<Item Att="3">C</Item>

<Item Att="4">D</Item>



and this function read all the attributes and content
of the Item node in the xml:

public void ReadXml()
int iCodepage = 862;
string sAttribute, sNodeValue;
string sFilePath = @"Test.xml";
StreamReader oFileStream = null;
XmlTextReader reader = null;
//@@@ Check if the file exists
if (!File.Exists(sFilePath))

//@@@ Get the file as XmlTextReader
oFileStream =
new StreamReader(sFilePath, Encoding.GetEncoding(iCodepage));
reader = new XmlTextReader(oFileStream);

//@@@ Loop through all the file
while (reader.Read())
//@@@ If we in Item node
if (reader.Name.Equals("Item") &&
(reader.NodeType == XmlNodeType.Element))
//@@@ Get the Attribute (Att) value
sAttribute = reader.Value;
//@@@ Get the node value
sNodeValue = reader.ReadInnerXml();

No comments: