【问题标题】:Retrieve fields in key value pair from XML using C#使用 C# 从 XML 中检索键值对中的字段
【发布时间】:2020-08-19 00:25:45
【问题描述】:

我有一个如下的 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?

【问题讨论】:

  • 1) 这不是有效的 XML - 2) 我看不到您的代码

标签: c# xml selenium selenium-webdriver xml-parsing


【解决方案1】:

使用 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; }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    相关资源
    最近更新 更多