How do I read and parse an XML file in C#?

后端 未结 11 2140
庸人自扰
庸人自扰 2020-11-21 23:03

How do I read and parse an XML file in C#?

11条回答
  •  -上瘾入骨i
    2020-11-21 23:36

    LINQ to XML Example:

    // 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);
    }
    

    Reference: LINQ to XML at MSDN

提交回复
热议问题