本文介紹了將 XML 轉(zhuǎn)換為通用列表的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在嘗試將 XML 轉(zhuǎn)換為列表
I am trying to convert XML to List
<School>
<Student>
<Id>2</Id>
<Name>dummy</Name>
<Section>12</Section>
</Student>
<Student>
<Id>3</Id>
<Name>dummy</Name>
<Section>11</Section>
</Student>
</School>
我使用 LINQ 嘗試了一些事情,但對(duì)繼續(xù)進(jìn)行不是很清楚.
I tried few things using LINQ and am not so clear on proceeding.
dox.Descendants("Student").Select(d=>d.Value).ToList();
計(jì)數(shù)為 2,但值類似于 2dummy12 3dummy11
Am getting count 2 but values are like 2dummy12 3dummy11
是否可以將上述 XML 轉(zhuǎn)換為具有 Id、Name 和 Section 屬性的 Student 類型的通用列表?
Is it possible to convert the above XML to a generic List of type Student which has Id,Name and Section Properties ?
我可以實(shí)現(xiàn)的最佳方式是什么?
What is the best way I can implement this ?
推薦答案
可以創(chuàng)建匿名類型
var studentLst=dox.Descendants("Student").Select(d=>
new{
id=d.Element("Id").Value,
Name=d.Element("Name").Value,
Section=d.Element("Section").Value
}).ToList();
這將創(chuàng)建一個(gè)匿名類型列表..
This creates a list of anonymous type..
如果要?jiǎng)?chuàng)建學(xué)生類型列表
If you want to create a list of Student type
class Student{public int id;public string name,string section}
List<Student> studentLst=dox.Descendants("Student").Select(d=>
new Student{
id=d.Element("Id").Value,
name=d.Element("Name").Value,
section=d.Element("Section").Value
}).ToList();
這篇關(guān)于將 XML 轉(zhuǎn)換為通用列表的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!