XML數(shù)據(jù)讀取方式性能比較
幾個月來,我一直在與XML操作打交道,熟悉了SOA(面向服務的架構(gòu))的使用,但是SQL的知識卻又忘得差不多了。最近我發(fā)現(xiàn)有四種常用的XML數(shù)據(jù)操作方式(主要是針對Java),但是我還沒有對這些方式進行
幾個月來,我一直在與XML操作打交道,熟悉了SOA(面向服務的架構(gòu))的使用,但是SQL的知識卻又忘得差不多了。最近我發(fā)現(xiàn)有四種常用的XML數(shù)據(jù)操作方式(主要是針對Java),但是我還沒有對這些方式進行實際的比較,也沒有看到網(wǎng)絡上有相關的實驗。所以我決定自己總結(jié)一下。
一、XmlDocument方式
```
static IList testXmlDocument()
{
var doc new XmlDocument();
doc.Load(xmlStream);
var nodeList ;
var lstChannel new List
foreach (XmlNode node in nodeList)
{
var channel new
{
Title ("title").InnerText,
Link ("link").InnerText,
Description ("description").InnerText,
Content ("content").InnerText,
PubDate ("pubDate").InnerText,
Author ("author").InnerText,
Category ("category").InnerText
};
(channel);
}
return lstChannel;
}
```
二、XPathNavigator方式
```
static IList testXmlNavigator()
{
var doc new XmlDocument();
doc.Load(xmlStream);
var nav ();
();
var nodeList ("/channel/item");
var lstChannel new List
foreach (XPathNavigator node in nodeList)
{
var channel new
{
Title ("title").Value,
Link ("link").Value,
Description ("description").Value,
Content ("content").Value,
PubDate ("pubDate").Value,
Author ("author").Value,
Category ("category").Value
};
(channel);
}
return lstChannel;
}
```
三、XmlTextReader方式
```
static List
{
var lstChannel new List
var reader (xmlStream);
while (())
{
if( "item" XmlNodeType.Element)
{
var channel new Channel();
(channel);
while (())
{
if ( "item")
break;
if ( ! XmlNodeType.Element)
continue;
switch ()
{
case "title":
channel.Title ();
break;
case "link":
();
break;
case "description":
();
break;
case "content":
();
break;
case "pubDate":
();
break;
case "author":
();
break;
case "category":
();
break;
default:
break;
}
}
}
}
return lstChannel;
}
```
四、Linq to XML方式
```
static IList testXmlLinq()
{
var xd XDocument.Load(xmlStream);
var list from node in xd.Elements("channel").Descendants("item")
select new
{
Title node.Element("title").Value,
Link node.Element("link").Value,
Description node.Element("description").Value,
Content node.Element("content").Value,
PubDate node.Element("pubDate").Value,
Author node.Element("author").Value,
Category node.Element("category").Value
};
return ();
}
```
測試結(jié)果
根據(jù)我的測試結(jié)果,以下是各個方式的執(zhí)行時間:
- XmlDocument:47ms
- XPathNavigator:42ms
- XmlTextReader:23ms
- Linq to XML:28ms
小結(jié)
經(jīng)過我的認識,XmlDocument的操作基本上按照W3C的DOM操作方式進行。不過要將全部節(jié)點解析成對象加載到內(nèi)存中,往往會造成很大的資源浪費。所以微軟官方也不推薦使用這種方式。因為我在這里讀取了所有的節(jié)點,所以性能和XPathNavigator方式相差不大。
在三種隨機讀取方式中,Linq to XML的性能最高,只是方法名有點別扭。而XmlTextReader方式是所謂的SAX(Simple API for XML)方式,它只能向前讀取,所以無疑性能最高。但是實現(xiàn)起來比較麻煩,需要精確控制訪問邏輯,并且無法使用匿名類來存儲數(shù)據(jù)。
在使用.NET 3.5之后,Xml Linq可以很好地取代前兩種方式。通常情況下,我們最好使用它。只有在個別場合,如果對性能要求極高,或者讀取的XML數(shù)據(jù)量太大無法一次性下載或讀取到內(nèi)存中,那就只能選擇使用XmlTextReader了。