解析 Visual Studio 测试资源管理器播放列表(解析 XML)

问题描述 投票:0回答:1

我正在尝试找到一种更好的方法来解析 Visual Studio 中保存的播放列表。这是 文件。这是已保存播放列表的示例:

<Playlist Version="2.0">
  <Rule Name="Includes" Match="Any">
    <Rule Match="All">
      <Property Name="Solution" />
      <Rule Match="Any">
        <Rule Match="All">
          <Property Name="Project" Value="MyProject" />
          <Rule Match="Any">
            <Rule Match="All">
              <Property Name="Namespace" Value="MyProject" />
              <Rule Match="Any">
                <Rule Match="All">
                  <Property Name="Class" Value="TestArc" />
                  <Rule Match="Any">
                    <Rule Match="All">
                      <Property Name="TestWithNormalizedFullyQualifiedName" Value="MyProject.TestArc.Insert_Arc" />
                      <Rule Match="Any">
                        <Property Name="DisplayName" Value="Insert_Arc" />
                      </Rule>
                    </Rule>
                    <Rule Match="All">
                      <Property Name="TestWithNormalizedFullyQualifiedName" Value="MyProject.TestArc.Insert_Arc_For_Construction" />
                      <Rule Match="Any">
                        <Property Name="DisplayName" Value="Insert_Arc_For_Construction(True)" />
                        <Property Name="DisplayName" Value="Insert_Arc_For_Construction(False)" />
                      </Rule>
                    </Rule>
                  </Rule>
                </Rule>
              </Rule>
            </Rule>
          </Rule>
        </Rule>
      </Rule>
    </Rule>
  </Rule>
</Playlist>

我所追求的是

values
properties
name
DisplayName。 通过使用示例 ,我想要的结果是三行,其中包括:

  1. 插入_圆弧
  2. Insert_Arc_For_Construction(真)
  3. Insert_Arc_For_Construction(假)

下面的代码解决了这个问题,但我觉得这不是“正确的”,也不是最好的方法,并且希望得到一些指示和更好的解决方案

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"vs-3-tests.playlist");

XmlNodeList nodeList = xmlDoc.SelectNodes("//Property");

int counter = 0;

foreach (XmlElement elem in nodeList)
{
    if (elem.HasAttributes)
    {
        if (elem.Attributes[0].Value == "DisplayName")
        {
            counter++;
            Console.WriteLine($"{counter} - {elem.Attributes[1].Value}");
        }
    }
}
c# xml xml-parsing
1个回答
0
投票

使用 Xml Linq :

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

namespace ConsoleApp10
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<string> values = doc.Descendants("Property").Where(x => (string)x.Attribute("Name") == "DisplayName").Select(x => (string)x.Attribute("Value")).ToList();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.