0. 准备:products.xml的定义:
<product id="product1" category="book">
<name>Programing Something</name>
<price>2000</price>
<publishDate>2008/10/10</publishDate>
<authors>
<author>Tarou Book</author>
<author>Hanako Book</author>
</authors>
</product>
<product id="product2" category="book">
<name>Administrating Something</name>
<price>5000</price>
<publishDate>2008/10/12</publishDate>
<authors>
<author>Kotarou Book1</author>
<author>Kohanako Book2</author>
</authors>
</product>
<product id="product3" category="novel">
<name>Suspection novel</name>
<price>500</price>
<publishDate>2007/12/12</publishDate>
<authors>
<author>Jirou Tarou</author>
</authors>
</product>
<product id="product4" category="novel">
<name>Fantasy novel</name>
<price>540</price>
<publishDate>2008/9/14</publishDate>
<authors>
<author>Tarou Book</author>
</authors>
</product>
<product id="product5" category="cram">
<name>Study English</name>
<price>2400</price>
<publishDate>2008/9/14</publishDate>
<authors>
<author>English Tarou</author>
<author>English Jirou</author>
</authors>
</product>
</products>
1.Linq To XML
1.1 加载XML文件
通过XDocument,XElement的Load方法读入XML文件,进行XDocument和XElement的初期化。
XElement elem = XElement.Load(@"D:/VisualStudioProject2008/Test/Linq2XML01/products.xml");
Console.WriteLine(elem);
XDocument doc = XDocument.Load(@"D:/VisualStudioProject2008/Test/Linq2XML01/products.xml");
Console.WriteLine(doc.ToString());
1.2 选择处理
如下代码所示,通过Linq对xml进行查询。
XElement products = XElement.Load(@"D:/VisualStudioProject2008/Test/Linq2XML01/products.xml");
var query = from p in products.Elements("product")
where (string)p.Attribute("category") == "book"
select new
{
ID = (string)p.Attribute("id"),
Name = (string)p.Element("name"),
Price = (decimal)p.Element("price")
};
foreach (var item in query)
{
Console.WriteLine(item);
}
执行结果如下:
{ ID = product1, Name = Programing Something, Price = 2000 }
{ ID = product2, Name = Administrating Something, Price = 5000 }
更复杂的应用,比如:通过Join一个String数组(书类型的集合)来查询。
view plainvar categories = new string[] { "book", "novel" };
// 在on里直接写p.Element("category")是无法编译通过的,
// 必须显示转换为string类型之后比较:(string) p.Element("category")
var query = from p in products.Elements("product")
let xCategory = (string) p.Attribute("category")
join c in categories
on xCategory equals c
orderby xCategory
select new
{
Name = (string)p.Element("name"),
Price = (decimal)p.Element("price"),
Category = xCategory
};
foreach (var item in query)
{
Console.WriteLine(item);
}
执行结果:
{ Name = Programing Something, Price = 2000, Category = book }
{ Name = Administrating Something, Price = 5000, Category = book }
{ Name = Suspection novel, Price = 500, Category = novel }
{ Name = Fantasy novel, Price = 540, Category = novel }