Trinh Minh Cuong Microsoft
Vietnam
5 phút với XML và XSLT
LINQ to XML
So sánh LINQ với các thư viện XML khác
5 phút với XML và XSLT
Một số định nghĩa
XSLT: Extensible Stylesheet Language
Transformations (XSLT) is an XML-based
language used for the transformation of XML
documents into other XML or "human-readable"
documents.
Xpath is a language for selecting nodes from
an XML document. In addition, XPath may be
used to compute values (strings, numbers, or
boolean values) from the content of an XML
document.
XSLT tutorial :
/>ntents.html
XSLT Demo #1
XSLT Demo #2: for-each
Câu hỏi
XSLT có template-matching, for-each, if,
sum … có thể viết thêm hàm cho XSLT bằng
C#.net
Làm thế nào thực hiện lệnh group by, join
trên XML như trong SQL?
XSLT và XLINQ có những điểm mạnh và yếu
khác nhau.
Dùng XSLT khi cần biến đổi dữ liệu từ cấu
trúc A -> B.
Dùng XLINQ khi cần truy vấn, tổng hợp, kết
hợp dữ liệu.
Cú pháp XLINQ đơn giản, dễ học hơn so với
XSLT, Xpath.
Câu hỏi
Tại sao Microsoft không tạo ra một
namespace System.LINQ
System.LINQ.xml
System.LINQ.sql
System.LINQ.dataset
System.LINQ.entity
Mà lại tạo ra:
System.Linq cho LINQ to Objects
System.Data.Linq cho DLINQ
System.Xml.Linq cho XLINQ
Class hierarchy của System.Xml.Linq
Cú pháp tạo dữ liệu XML trong LINQ đơn giản hơn
Xem ví dụ so sánh CreateXMLbyDOM với CreateXMLbyLINQ
Với VB, có thể gán thẳng chuỗi XML vào biến kiểu XElement
Select có điều kiện
public IEnumerable<XElement>
SelectCDPriceHigherThan(double price)
{
return from cd in rootElement.Elements("CD")
where (Convert.ToDouble(cd.Element("PRICE").Value) >
price)
select cd;
}
public IEnumerable<GroupByObj> GroupCDByCountry()
{
return from cd in rootElement.Elements("CD")
group cd by cd.Element("COUNTRY").Value into g
select new GroupByObj (g.Key,g);
}
Group by
Group by and Aggregation
public IEnumerable<XElement> AveragePriceInEachCountry()
{
return from cd in rootElement.Elements("CD")
group cd by cd.Element("COUNTRY").Value into g
select new XElement("AveragePricePerCountry",
new XAttribute("Country", g.Key),
new XAttribute("AveragePrice",
g.Average(cd =>
Convert.ToDouble(cd.Element("PRICE").Value))));
}
Thay đổi dữ liệu trong XML
public void UpdatePriceOfCD(string CDTitle, double
new_price)
{
IEnumerable<XElement> result = from cd in
rootElement.Elements("CD")
where
cd.Element("TITLE").Value.Equals(CDTitle)
select cd;
foreach (XElement cd in result)
{
cd.SetElementValue("PRICE", new_price.ToString());
//Update price
}
foreach (XElement cd in result)
{
Console.WriteLine("{0} has new price is {1}",
cd.Element("TITLE").Value, cd.Element("PRICE").Value);
}
}