C# LINQ to XML應用介紹

來源:互聯網
上載者:User

W3C制定了XML DOM標準,.Net為了支援W3C的標準,從1.1版本開始就引入了XmlDocument類。我在前一篇部落格中,介紹了如何使用XmlDocument類來對XML文檔進行操作。後來 .Net又引入了LINQ,於是LINQ to XML也就應運而生,所以在.Net中,不僅可以用W3C XML DOM標準,還可以使用LINQ to XML來操作XML文檔。下面就來簡單介紹一下如何使用LINQ to XML。
(一) 載入
載入XML比較常用的有三種方法: 複製代碼 代碼如下:public static XDocument Load(string uri);
public static XDocument Load(Stream stream);
public static XDocument Parse(string text);

下面代碼示範如何使用它們: 複製代碼 代碼如下:// public static XDocument Load(string uri);
// uri 即為要裝載的檔案名稱
var doc1 = XDocument.Load("XMLFile1.xml");
// public static XDocument Load(Stream stream);
Entity retrievedAnnotation = _orgService.Retrieve("annotation"
, new Guid("C1B13C7F-F430-E211-8FA1-984BE1731399"), new ColumnSet(true));
byte[] fileContent = Convert.FromBase64String(retrievedAnnotation["documentbody"].ToString());
MemoryStream ms = new MemoryStream(fileContent);
XDocument xDoc = XDocument.Load(ms);
// public static XDocument Parse(string text);
string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>";
var doc2 = XDocument.Parse(str);

(二) 查詢
我們以下面的XML文檔為例: 複製代碼 代碼如下:<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer id="01" city="Beijing" country="China">Lenovo
<Order OrderID="1001" Freight="36.00" />
<Order OrderID="1003" Freight="61.50" />
</Customer>
<Customer id="02" city="Amsterdam" country="The Netherlands">Shell
<Order OrderID="1002" Freight="56.65" />
<Order OrderID="1004" Freight="65.50" />
<Order OrderID="1005" Freight="100.50" />
</Customer>
</Customers>

1. 返回所有Customer 節點: 複製代碼 代碼如下:var result = from customer in doc1.Descendants("Customer")
select customer.Value;
foreach (var s in result)
{
Console.WriteLine(s);
}

輸出結果:
Lenovo
Shell
2. 返回id為02並且 city 為 Amsterdam 的customer : 複製代碼 代碼如下:var result = (from customer in doc1.Descendants("Customer")
where (string)customer.Attribute("id") == "02" && (string)customer.Attribute("city") == "Amsterdam"
select customer.Value).FirstOrDefault();
Console.WriteLine(result);

輸出結果:
Shell
3. 尋找出 order ID 1003的customer ID和它的freight: 複製代碼 代碼如下:var result = (from order in doc1.Descendants("Order")
where order.Attribute("OrderID").Value == "1003"
select new
{
CustomerID = order.Parent.Attribute("id").Value,
Freight = (decimal)order.Attribute("Freight")
}).FirstOrDefault();
Console.WriteLine(string.Format("Customer ID: {0} Freight: {1}", result.CustomerID, result.Freight));

輸出結果:
Customer ID: 01 Freight: 61.50
4. 查詢每個客戶的freight的總和 複製代碼 代碼如下:var result = from customer in doc1.Descendants("Customer")
select new
{
CustomerName = customer.Value,
TotalFreight = customer.Descendants("Order").Sum(o => (decimal)o.Attribute("Freight"))
};
foreach (var r in result)
{
Console.WriteLine(string.Format("Customer: {0} Total Freight: {1}", r.CustomerName, r.TotalFreight));
}

輸出結果:
Customer: Lenovo Total Freight: 97.50
Customer: Shell Total Freight: 222.65
5. 使用LINQ to XML Join
Join可以用在LINQ to XML和其他的LINQ providers,比如說LINQ to Objects。下面的代碼展示了如何將一個數組和一個XML檔案Join起來。 複製代碼 代碼如下:string[] orders = {"1001", "2000", "1002"};
var result = from order in doc1.Descendants("Order")
join selected in orders
on (string)order.Attribute("OrderID") equals selected
select new
{
CustomerName = order.Parent.Value,
OrderID = selected,
Freight = (decimal)(order.Attribute("Freight"))
};
foreach (var r in result)
{
Console.WriteLine(string.Format("Customer ID: {0} Order:{1} Freight: {2}", r.CustomerName, r.OrderID, r.Freight));
}

輸出結果:
Customer ID: Lenovo Order:1001 Freight: 36,00
Customer ID: Shell Order:1002 Freight: 56,65
(三) 建立
以建立以下XML文檔為例: 複製代碼 代碼如下:<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer id="01" city="Beijing" country="China" name="Lenovo">
<Order OrderID="1001" Freight="36.00" />
</Customer>
</Customers>

複製代碼 代碼如下:var doc = new XDocument(
new XElement("Customers",
new XElement("Customer",
new XAttribute("id", "01"),
new XAttribute("city", "Beijing"),
new XAttribute("country", "China"),
new XAttribute("name", "Lenovo"),
new XElement("Order",
new XAttribute("OrderID", "1001"),
new XAttribute("Freight", "36.00")
)
)
)
);
doc.Save("test.xml");

總結:
1. XDocument提供了對XML文檔在記憶體中的隨機的讀寫操作。
2. XDocument使用LINQ to XML來讀取XML結點。
3. 你可以通過LINQ投射(projection)來將XML變換為Object。
4. LINQ投射可以將XML變換為IEnumerable<String>。
5. LINQ投射可以將XML變換為其他格式的XML。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.