C# V: 读取XML文件

 

在C#中读取XML有LINQ版本和非LINQ版本。
LINQ版本:

// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");


// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
            where (int)c.Attribute("id") < 4
            select c.Element("firstName").Value + " " +
                   c.Element("lastName").Value;


foreach (string name in query)
{
    Console.WriteLine("Contact's Full Name: {0}", name);
}

详情参阅MSDN的文章

非LINQ版本:

XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
foreach(XmlNode node in doc.DocumentElement.ChildNodes){
   string text = node.InnerText; //or loop through its children as well
   string attr = node.Attributes["theattributename"]?.InnerText;
}

是为之记。
Alva Chien
2016.8.23

 

posted @ 2016-08-23 18:40  会拍照能修图的码农  阅读(139)  评论(0)    收藏  举报