首页 新闻 赞助 找找看

多层xml 使用linqToXml怎么读取?

0
悬赏园豆:20 [已关闭问题] 关闭于 2012-02-13 17:00
<!-- XML结构如下-->
<votes>
<item>
<id>1</id>
<title>三年一班</title>
<options>
<option name="张三"></option>
<option name="李四"></option>
<option name="王五"></option>
</options>
</item>
<item>
<id>2</id>
<title>三年2班</title>
<options>
<option name="张三"></option>
<option name="李四"></option>
<option name="王五"></option>
</options>
</item>
</votes>


我用Linq去读取,并且select new一个新的对象出来...  id和title很好弄 可是options列表怎么弄? 代码如下:

var xml = XDocument.Load(xmlPath);

var items = from s in xml.Element("votes").Elements("item")
select new {
Id=int.Parse(s.Element("id").Value),
Title=s.Element("title").Value,
//Options.add(s.Elements("option").Take(0)) 这步是错误的,我该怎么写?
};
coder_wang的主页 coder_wang | 初学一级 | 园豆:193
提问于:2012-02-13 16:50
< >
分享
所有回答(3)
0

自己尝试解决了,这样即可...  果然是面向对象啊

var items = from s in xml.Element("votes").Elements("item")
select new
{
Id = int.Parse(s.Element("id").Value),
Title = s.Element("title").Value,
Options = from t in s.Element("options").Elements("option")
select new {
Name=t.Attribute("name").Value,
Pinyin = t.Attribute("pinyin").Value,
Description = t.Attribute("description").Value
}
};
coder_wang | 园豆:193 (初学一级) | 2012-02-13 16:59
1

再给你一个方式

Options = s.Element("options").Descendants().Select(ele=>ele.Attribute("name").Value).ToList()
LCM | 园豆:6876 (大侠五级) | 2012-02-13 17:20

不错 你的简单多了~~

支持(0) 反对(0) coder_wang | 园豆:193 (初学一级) | 2012-02-17 16:20
0

试试

DataSet ds = new DataSet();
ds.ReadXml(XMLFilePath);
return ds.Tables[0];

这时候调试看看ds是什么情况

pasig10038 | 园豆:387 (菜鸟二级) | 2012-10-02 11:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册