//读取XML文档并返回对象列表
static IEnumerable<Customer> CreateCustomers()
{
var results = from c in XDocument.Load("Customers.xml").
Descendants("Customer")
select new Customer
{
City = c.Attribute("City").Value,
CustomerID = c.Attribute("CustomerID").Value
};
return results;
}
//显示XML文档里的内容
public static void XMLQuery()
{
var doc = XDocument.Load("Customers.xml");
Console.WriteLine(doc);
}
//查询XML並轉換
public static void XMLSearch()
{
//查詢顯示
var doc = XDocument.Load("Customers.xml");
var results = from c in doc.Descendants("Customer2") where c.Attribute("City").Value == "London2" select c;
foreach (var item in results)
{
Console.WriteLine(item + "\n");
}
XElement transformedResulets = new XElement("Contacts", from customer in results
select new XElement("Contact",
new XAttribute("ID", customer.Attribute("CustomerID").Value),
new XElement("Name", customer.Attribute("ContactName").Value),
new XElement("City", customer.Attribute("City").Value)));
Console.WriteLine("Results:\n{0}", transformedResulets);
//將轉換的XML保存到新的XML中
transformedResulets.Save("Output.xml");
}
}
//实体对象
public class Customer
{
public string CustomerID { get; set; }
public string City { get; set; }
public override string ToString()
{
return CustomerID + "\t" + City;
}
}