如何使用XML和LINQ [英] How to use XML and LINQ

查看:46
本文介绍了如何使用XML和LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用.net 4.5 VS 2012

Using .net 4.5 VS 2012

我正在尝试从XMl文件读取数据

I am trying to read the data from a XMl file

<?xml version="1.0" encoding="utf-8"?>
<userCategories>
  <Cat>General</Cat>
  <Cat>Science</Cat>
  <Cat>HelloWorld</Cat>
</userCategories>

这是我编写的代码:

//create XML document from file
XDocument myCatList = XDocument.Load(categoryPath);
//get all categories using LINQ
var myCategories =
    from element in myCatList.Descendants("userCategories")
//select all elements in XML where Element has name Cat - mean all if file like i write before
    select element.Element("Cat").Value;
    //create string for result
string data = String.Empty;
use foreach for getting all categories
foreach (var userCat in myCategories)
{
    //put in one string 
    data += string.Format("{0}\n", userCat);
}

因此,我认为这种LINQ请求必须返回具有所有值的字符串数据(常规\ n科学\ n HelloWorld \ n).但结果我只得到了将军.

So I think that this kind of LINQ request must return me a string data with all values (General \n Science \n HelloWorld \n). but as result i got only General.

我错过了什么?为什么我只从XML中获得Item General而不是所有节点?

What have I missed? Why do I get only the Item General instead of all of the nodes from the XML?

推荐答案

myCatList.Descendants("userCategories")返回名为<userCategories>的所有元素的集合. 您只有一个这样的元素.

myCatList.Descendants("userCategories") returns the collection of all elements named <userCategories>.
You only have one such element.

select element.Element("Cat")返回每个元素中的第一个<Cat>子代.

select element.Element("Cat") returns the first <Cat> child in each of those elements.

您要选择所有<Cat>元素:

from elem myCatList.Descendants("cat")
select elem.Value

这篇关于如何使用XML和LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆