Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

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}
", userCat);
}

So I think that this kind of LINQ request must return me a string data with all values (General Science HelloWorld ). 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 + "
"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...