我正在尝试找到一种更好的方法来解析 Visual Studio 中保存的播放列表。这是 xml 文件。这是已保存播放列表的示例:
<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。
通过使用示例 xml,我想要的结果是三行,其中包括:
下面的c#代码解决了这个问题,但我觉得这不是“正确的”,也不是最好的方法,并且希望得到一些指示和更好的解决方案
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}");
}
}
}
使用 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();
}
}
}