1.多采购订单
XElement elements = XElement.Load(Server.MapPath("../Linqxml/PurchaseOrders.xml"));
/*示例演示如何查找具有 Type 属性等于“Shipping”的子 Address 元素和等于“NY”的子 State
元素的所有 PurchaseOrder 元素。示例在 Where 子句中使用嵌套查询,如果集合中有任何元素,则 Any 运算符返回 true */
IEnumerable<XElement> Elements = from el in elements.Elements("PurchaseOrder")
where
(
from add in el.Elements("Address")
where
(string)add.Attribute("Type") == "Shipping" &&
(string)add.Element("State") == "NY"
select add
).Any()
select el;
foreach (XElement el in Elements)
{
Console.WriteLine((string)el.Attribute("PurchaseOrderNumber"));
}
2.创建XML
信息如下
<Books>
<Book title="LINQ">
<Publisher>Mirosoft</Publisher>
<year>2010</year>
</Book>
<Book title="C# 4.0">
<Publisher>Mirosoft</Publisher>
<year>2010</year>
</Book>
<Book title="SQL2008">
<Publisher>Mirosoft</Publisher>
<year>2010</year>
</Book>
</Books>
C#
class book
{
public string title;
public string publisher;
public int year;
public book(string title, string publisher, int year)
{
this.title = title;
this.publisher = publisher;
this.year = year;
}
}
class InitialArray
{
static void Main()
{
book[] myBook = new book[]
{
new book("LINQ","Mirosoft",2010),
new book("C# 4.0","Mirosoft",2010),
new book("SQL2008","Mirosoft",2010)
};
XElement Element = new XElement("Books",
from books in myBook
select
new XElement("Book", new XAttribute("title", books.title),
new XElement("Publisher", books.publisher),
new XElement("year", books.year)));
Console.WriteLine(Element);
}
}