本文介紹了將 XML 轉換為通用列表的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試將 XML 轉換為列表
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 嘗試了一些事情,但對繼續進行不是很清楚.
I tried few things using LINQ and am not so clear on proceeding.
dox.Descendants("Student").Select(d=>d.Value).ToList();
計數為 2,但值類似于 2dummy12 3dummy11
Am getting count 2 but values are like 2dummy12 3dummy11
是否可以將上述 XML 轉換為具有 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 ?
我可以實現的最佳方式是什么?
What is the best way I can implement this ?
推薦答案
可以創建匿名類型
var studentLst=dox.Descendants("Student").Select(d=>
new{
id=d.Element("Id").Value,
Name=d.Element("Name").Value,
Section=d.Element("Section").Value
}).ToList();
這將創建一個匿名類型列表..
This creates a list of anonymous type..
如果要創建學生類型列表
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();
這篇關于將 XML 轉換為通用列表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!