Linq 操作XML文件
时间:2011-05-08 来源:※森林小居※
1.创建Xml树
<person id="1"> <name>Gaby</name> <age>12</age> <address>GuangZhou</address> </person> <person id="2"> <name>Bill</name> <age>33</ag e> <address>USA</address> </person> <person id="3"> <name>BiLy</name> <age>19</age> <address>HuNan</address> </person>如果要创建如上的XML树:
代码示例:
XElement xmlTree = new XElement("Root",
new XElement("person", new XElement("name", "Gaby"),
new XElement("age",18),
new XElement("address","GuangZhou")),
new XElement("person", new XElement("name", "Lily"),
new XElement("age",20),
new XElement("address","USA")),
new XElement("person", new XElement("name", "Bill"),
new XElement("age",55),
new XElement("address","English"))
);
foreach (var item in xmlTree.Elements())
{
Console.WriteLine(item);
}
输出结果:
2.读取XML文件
有以下XML文件:path:D:\NetDemo\LinqToXml\LinqToXml\XMLFile.xml
<?xml version="1.0" encoding="utf-8" ?>
<persons>
<person id="1">
<name>Gaby</name>
<age>16</age>
<address>GuangZhou</address>
</person>
<person id="2">
<name>Bill</name>
<age>33</age>
<address>USA</address>
</person>
<person id="3">
<name>BiLy</name>
<age>19</age>
<address>HuNan</address>
</person>
<person id="4">
<name>James</name>
<age>16</age>
<address>English</address>
</person>
</persons>
读取方法一: XElement xml = XElement.Load(@"D:"NetDemo"LinqToXml"LinqToXml"XMLFile.xml"); Console.WriteLine("读取XML..."); foreach (var item in xml.Elements("person")) { Console.WriteLine(item.Element("name").Value+""t" +item.Element("age").Value+""t" +item.Element("address").Value); } 读取方法二:(查询表达式) var persons = from p in xml.Elements("person") select new { Name = p.Element("name").Value, Age = p.Element("age").Value, Address = p.Element("address").Value};
Console.WriteLine("读取XML...");
foreach (var item in persons) { Console.WriteLine(item.Name+"\t"+item.Age+"\t"+item.Address); } 读取方法三:(lambada表达式) var persons = xml.Elements("person").Select(p => new{Id=p.Attribute("id").Value, //读取属性 Name = p.Element("name").Value, Age = p.Element("age").Value, Address = p.Element("address").Value } ); foreach (var item in persons) { Console.WriteLine(item.Name + ""t" + item.Age + ""t" + item.Address); }
输出结果(相同):