2016 - 2024

感恩一路有你

XML数据读取方式性能比较

浏览量:1947 时间:2024-01-31 11:20:04 作者:采采

几个月来,我一直在与XML操作打交道,熟悉了SOA(面向服务的架构)的使用,但是SQL的知识却又忘得差不多了。最近我发现有四种常用的XML数据操作方式(主要是针对Java),但是我还没有对这些方式进行实际的比较,也没有看到网络上有相关的实验。所以我决定自己总结一下。

一、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 testXmlReader()

{

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

}

```

测试结果

根据我的测试结果,以下是各个方式的执行时间:

- XmlDocument:47ms

- XPathNavigator:42ms

- XmlTextReader:23ms

- Linq to XML:28ms

小结

经过我的认识,XmlDocument的操作基本上按照W3C的DOM操作方式进行。不过要将全部节点解析成对象加载到内存中,往往会造成很大的资源浪费。所以微软官方也不推荐使用这种方式。因为我在这里读取了所有的节点,所以性能和XPathNavigator方式相差不大。

在三种随机读取方式中,Linq to XML的性能最高,只是方法名有点别扭。而XmlTextReader方式是所谓的SAX(Simple API for XML)方式,它只能向前读取,所以无疑性能最高。但是实现起来比较麻烦,需要精确控制访问逻辑,并且无法使用匿名类来存储数据。

在使用.NET 3.5之后,Xml Linq可以很好地取代前两种方式。通常情况下,我们最好使用它。只有在个别场合,如果对性能要求极高,或者读取的XML数据量太大无法一次性下载或读取到内存中,那就只能选择使用XmlTextReader了。

版权声明:本文内容由互联网用户自发贡献,本站不承担相关法律责任.如有侵权/违法内容,本站将立刻删除。