xml文件:
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book>
<name>Book1</name>
<price>10</price>
<points>1</points>
</book>
<book>
<name>Book2</name>
<price>20</price>
<points>10</points>
</book>
</books>
如何阅读:(我做了一个小助手类“书籍”,只是为了保持清洁,但你不必这样做,你也可以使用匿名类型)
public class Books
{
public string name { get; set; }
public double price {get;set;}
public int points { get; set; }
}
阅读 xmlfile: (你必须为此导入using System.Xml.Linq;
命名空间)
XDocument doc = XDocument.Load("PathToYourXml.xml");
List<Books> books = (from x in doc.Descendants("book")
select new Books
{ name = x.Element("name").Value,
price = Convert.ToDouble(x.Element("price").Value),
points = Convert.ToInt32(x.Element("points").Value)
}).ToList();
打印结果:
foreach (Books i in books)
{
Console.WriteLine(i.name + " " + i.price + " " + i.points);
}