下面列出微软.net类库提供的读写xml文件个类及其特点:
类名称 | 优点 | 缺点 |
XmlReader | 快速、高效、可扩展 | 只读,只向前,需要人工验证 |
XmlDocument | 可往返、可读写、支持XPath筛选 | 比XmlReader慢 |
XPathNavigator | 可往返,支持XPath和XSLT | 只读 |
XPathDocument | 比XmlDocument,优化支持XPath和XSLT | 比XmlReader慢 |
本文提到的XmlReader也是微软类库中的一个类,它的特点是快速高效,并且可扩展,缺点是只读。
本人关于这三个做了一个性能测试
条件:做100000次,每次都进行XML的加载和一个节点的读取,所共的时间如下
xpath: 03.265625
dom: 02.625
xmlreader: 0.140625
其中xpath和dom比较类似,大部分时间都在加载XML上,节点查找倒是挺快的,而xmlreader则是边加载边查找,不需要完全加载完才开始查找节点,可以用于大容量的XML读取,便代码编写上没有前两个快捷
DateTime dt1, dt2;
string linkId;
dt1 = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
linkId = XPathTest(strXml);
}
dt2 = DateTime.Now;
Console.WriteLine("XPathTest: {0}", dt2 - dt1);
dt1 = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
linkId = DOMTest(strXml);
}
dt2 = DateTime.Now;
Console.WriteLine("DOMTest: {0}", dt2 - dt1);
dt1 = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
linkId = XmlReaderTest(strXml);
}
dt2 = DateTime.Now;
Console.WriteLine("XmlReaderTest: {0}", dt2 - dt1);
//XmlStream.Close();
Console.ReadLine();
#region XPathTest
static string XPathTest(string strXml)
{
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.LoadXml(strXml);
//XmlNode linkId0 = XmlDoc.SelectSingleNode("Response/SessionID");
//XmlNode linkId1 = XmlDoc.SelectSingleNode("Response/Result/Item/LastFeed");
//XmlNode linkId2 = XmlDoc.SelectSingleNode("Response/Result/Item/LandStatus");
//XmlNode linkId3 = XmlDoc.SelectSingleNode("Response/Result/Item/AnimalID");
//XmlNode linkId4 = XmlDoc.SelectSingleNode("Response/Result/Item/RaiseTime");
//XmlNode linkId5 = XmlDoc.SelectSingleNode("Response/Result/Item/AnimalName");
XmlNode linkId = XmlDoc.SelectSingleNode("Response/Result/Item/LandID");
return linkId.InnerXml;
}
#endregion
#region DOMTest
static string DOMTest(string strXml)
{
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.LoadXml(strXml);
//XmlNode linkId0 = XmlDoc["Response"]["SessionID"];
//XmlNode linkId1 = XmlDoc["Response"]["Result"]["Item"]["LastFeed"];
//XmlNode linkId2 = XmlDoc["Response"]["Result"]["Item"]["LandStatus"];
//XmlNode linkId3 = XmlDoc["Response"]["Result"]["Item"]["AnimalID"];
//XmlNode linkId4 = XmlDoc["Response"]["Result"]["Item"]["RaiseTime"];
//XmlNode linkId5 = XmlDoc["Response"]["Result"]["Item"]["AnimalName"];
XmlNode linkId = XmlDoc["Response"]["Result"]["Item"]["LandID"];
return linkId.InnerXml;
}
#endregion
#region XmlReaderTest
static string XmlReaderTest(string strXml)
{
string restr = "";
MemoryStream XmlStream = new MemoryStream();
byte[] bytes = Encoding.UTF8.GetBytes(strXml);
XmlStream.Write(bytes, 0, bytes.Length);
XmlStream.Position = 0;
XmlTextReader reader = new XmlTextReader(new StreamReader(XmlStream));
while (reader.Read() && reader.Name != "Response") ;
while (reader.Read() && reader.Name != "Result") ;
while (reader.Read() && reader.Name != "Item") ;
while (reader.Read() && reader.Name != "LandID") ;
restr = reader.ReadString();
XmlStream.Close();
return restr;
}
#endregion