[英]Retrieve fields in key value pair from XML using C#
我有一个 XML 如下:
<test-run>
<test-suite>
<test-suite>
<test-case id="1234" name="ABC" result="Passed">
</test-case>
</test-suite>
</test-suite>
</test-run>
这是我正在使用的示例 XML 文件。 如何使用 C# 从中检索 id、name 和 Result?
使用 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; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.