Friday, April 24, 2009

Don't use XmlDocument use XmlTextReader instead

Hi,
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" ?>

<RootNode>

<Child>

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

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

</Child>

<Child>

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

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

</Child>

</RootNode>



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))
return;

//@@@ 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
reader.MoveToAttribute("Att");
sAttribute = reader.Value;
Console.WriteLine(sAttribute);
//@@@ Get the node value
reader.MoveToElement();
sNodeValue = reader.ReadInnerXml();
Console.WriteLine(sNodeValue);
}
}
}

No comments: