Linq to XML读取xml的方法
添加应用:using System.Xml.Linq;
读取xml最重要的要知道xml是那种写法,因为linq已经把读取方式封装的相对傻瓜了,要有问题一定xml的结构问题。
第一种写法:
<?xml version="1.0" encoding="utf-8" ?>
<feeds>
<feed>
<image>ddddddddd</image>
<link>fffffffff</link>
<title>ddddddddddddddddd</title>
</feed>
</feeds>
Linq语句:
XDocument xdoc= XDocument.Load(Server.MapPath("xxx.xml"));
var ad = from a in xdoc.Descendants("feed")
select new
{
image = a.Element("image").Value,
link = a.Element("link").Value,
title = a.Element("title").Value
};
foreach (var a in ad)
Response.Write(a.image);
第二种xml
<?xml version="1.0" encoding="utf-8" ?>
<BizADsList>
<adData aid="1" image="815.jpg" link="http://www.dizhitiao.com" title="测试1"/>
<adData aid="2" image="5815.jpg" link="http://www.dizhitiao.com" title="测试2"/>
</BizADsList>
Linq语句:
XDocument adList = XDocument.Load(Server.MapPath("Data.xml"));
var ad = from a in adList.Descendants("BizADsList").Elements("adData")
select new
{
image = a.Attribute("image").Value,
link = a.Attribute("link").Value,
title = a.Attribute("title").Value
};
string s = "";
foreach (var a in ad)
s += a.image;
别告诉我没看出区别来。总之一句话,对xml要先多些了解。