almost 9 years ago
在.Net 3.5之前,要在程式中讀取XML檔案,必須要使用xmlDocument去做讀取以及寫入的動作
而在.Net 3.5之後,微軟提供了更方便好用的Linq to XML
一樣的,在使用之前要先using
using System.XML.Linq;
接著就是開啟XML檔
XDocument doc = XDocuments.Load("sample.xml");
然後節點的讀取
/* 單一節點 */
XElement ele = doc.Element("NodeA");
/* 多節點 */
IEnumerable<XElement> allEle = doc.Elements("NodeB");
屬性的讀取
XAttribute att = ele.Attribute("AttbuteA");
InnerText的讀取
string text = ele.Value;
OK,以上是用傳統xmlDocument的做法來描述的
而下面呢,就來看一下Linq to XML的強大之處吧
首先,如果你有一個XML如下:
<?xml version="1.0" encoding="utf-8" ?>
<application>
<myClass Name="五年一班">
<ClassRoom>A棟301</ClassRoom>
<ClassMate Name="王大偉">
<Gender>男</Gender>
<Score>普通</Score>
</ClassMate>
<ClassMate Name="吳小芬">
<Gender>女</Gender>
<Score>優良</Score>
</ClassMate>
</myClass>
</application>
這時候如果我們要知道你有哪些同學的話,只需要這樣做
/* 注意!var變數宣告為個人使用習慣,若不知道其用法請使用 IEnumerable<XElement> */
var allClassMates = XDocument.Load("sample.xml").Root.Element("myClass").Elements("Class");
在這邊,使用XDocument.Load("sample.xml").Root
可以忽略根節點的名稱<application>
也就是說不管根節點叫什麼名字,我都可以不用管,這是我個人的習慣用法
在這個範例中,其結果會跟直接使用XDocument.Load("sample.xml").Element("application")
是一樣的
執行完上面的程式後,接著就可以讀取各同學的詳細資訊
/* 注意!var變數宣告為個人使用習慣,若不知道其用法請使用 XElement */
foreach(var person in allClassMates)
{
string name = person.Attribute("Name").Value; // 屬性
string gender = person.Element("Gender").Value; // InnerText
string score = person.Element("Score").Value; // InnerText
}
這樣跟傳統的XmlDocument比起來,是不是很直觀好用呢