简体   繁体   中英

Retrieve fields in key value pair from XML using C#

I have an XML as below:

<test-run>
 <test-suite>
 <test-suite>
   <test-case id="1234" name="ABC" result="Passed">
   </test-case>
 </test-suite>
 </test-suite>
</test-run>

This is an example XML file that I am using. How to retrieve id,name and Result from this using C#?

Using xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            List<Result> results = doc.Descendants("test-case").Select(x => new Result()
            {
                id = (string)x.Attribute("id"),
                name = (string)x.Attribute("name"),
                result = (string)x.Attribute("result")
            }).ToList();
        }
    }
    public class Result
    {
        public string id { get; set; }
        public string name { get; set; }
        public string result { get; set; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM