在是用LINQ的时候能够把多个数据源混合。html
下面是用LINQ to SQL 查询 Northwind数据库中的表结果再把提取的结果转换成XML文档。数据库
创建一个Northwind.dbml 详细能够看LINQ to SQL服务器
从服务器资源管理器拖动两个表到设计器中,设计器结果以下,并自动创建关联设计
代码以下: code
public void MyLingSqlAndXml() { NorthwindDataContext dc = new NorthwindDataContext(); XElement xe = new XElement("Customers", //根元素 from c in dc.Customers //查询数据库的结果 select new XElement("Customer", //创建新的XML元素 new XElement("CustomerId", c.CustomerID), //元素的每一条子元素 new XElement("CompanyName", c.CompanyName), new XElement("Country", c.Country), new XElement("OrderNum", c.Orders.Count)) ); xe.Save(@"C:\myCustomers.xml"); Response.Write("File created"); }
运行以上代码,会在C盘根目录生成一个XML文件,部份内容以下:xml
<?xml version="1.0" encoding="utf-8"?> <Customers> <Customer> <CustomerId>ALFKI</CustomerId> <CompanyName>Alfreds Futterkiste</CompanyName> <Country>Germany</Country> <OrderNum>6</OrderNum> </Customer> <Customer> <CustomerId>ANATR</CustomerId> <CompanyName>Ana Trujillo Emparedados y helados</CompanyName> <Country>Mexico</Country> <OrderNum>4</OrderNum> </Customer> <Customer> <CustomerId>ANTON</CustomerId> <CompanyName>Antonio Moreno Taquería</CompanyName> <Country>Mexico</Country> <OrderNum>7</OrderNum> </Customer>