当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to use XML and LINQ

问题描述:

Using .net 4.5 VS 2012

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>

This is the code that I wrote:

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

}

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.

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

网友答案:

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

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

You want to select all of the <Cat> elements:

from elem myCatList.Descendants("cat")
select elem.Value
网友答案:

Using Aggregate also we can solve the problem

XDocument myCatList = XDocument.Load(@"D:\a.xml");    
var myCategories = myCatList.Elements("userCategories").Descendants("Cat").Select(s => s.Value).Aggregate(new StringBuilder(), (s,i) => s.Append(i + "\n"));
分享给朋友:
您可能感兴趣的文章:
随机阅读: