【LINQ笔记】LINQ操作XML
加载XML
XElement.Load("c:/1.xml");
XElement.Parse("<Persons></Persons>");
查找元素
var l = from n in root3.Elements()
select new Person { ID = int.Parse(n.Element("ID").Value), Name = n.Element("Name").Value };
构造XML
var root = new XElement("Persons",
new XElement("Person",
new XElement("ID", 1),
new XElement("Name", "zhangsan")),
new XElement("Person",
new XElement("ID", 2),
new XElement("Name", "lisi")),
new XElement("Person",
new XElement("ID", 3),
new XElement("Name", "wangwu"))
);
root.Save("c:/1.xml");
list转XML
var personList = new List<Person> {
new Person{ ID=1,Name="fan1"},
new Person{ ID=2,Name="fan2"}
};
var root2 = new XElement("Persons",
(from p in personList
select new XElement("Product", new XAttribute("ID", p.ID),
new XElement("Name", p.Name)))
);
root2.Save("d:/2.xml");
生成XML:
<?xml version="1.0" encoding="utf-8"?>
<Persons>
<Product ID="1">
<Name>fan1</Name>
</Product>
<Product ID="2">
<Name>fan2</Name>
</Product>
</Persons>
DataTable转XML
DataTable table = GetTable();
var root3 = new XElement("Persons",
(from n in table.AsEnumerable()
select new XElement("Product", new XElement("ID", n.Field<int>("ID")),
new XElement("Name", n.Field<string>("Name")))
));
root3.Save("c:/3.xml");