<?xml version='1.0' encoding='utf-8'?>
<automationSettings>
<VM name="DE-123" language="de" powerOn="true">
<vmClients>
<vmClient name="KO-123" language="ko"/>
<vmClient name="US-123" language="en"/>
<vmClient name="FR-123" language="fr"/>
</vmClients>
</VM>
<VM name="ES-123" language="en" powerOn="true">
<vmClients>
<vmClient name="IT-123" language="it"/>
<vmClient name="JA-123" language="ja"/>
</vmClients>
</VM>
</automationSettings>
我有一个C#方法,当VM元素具有匹配的名称时,该方法应该返回vmClient name属性的所有值。例如,我想获取名称为“DE-123”的VM的vmClient名称。这是我尝试的代码,但它没有返回任何东西。我究竟做错了什么?感谢您提供的任何帮助。
public static void GetClientsList(string systemName)
{
systemsFilePath = "text.xml";
string listOfClients = string.Empty;
try
{
var xdoc = XDocument.Load(systemsFilePath);
var query = from vm in xdoc.Root.Descendants("VM").Descendants("vmClients").Elements()
where vm.Attribute("name").Value == systemName
select new
{
Name = (string)vm.Attribute("name").Value
};
var vms = query.ToList();
for (int i = 0; i < vms.Count; i++)
{
listOfClients += vms[i].Name + " ";
}
Global.epoClients = listOfClients;
}
catch (Exception ex)
{
Console.WriteLine("GetClientsList exception: " + ex.Message);
}
}
}
答案 0 :(得分:1)
我怀疑你真的想要:
var query = xdoc.Root.Descendants("VM")
.Where(vm => (string) vm.Attribute("name") == systemName)
.Descendants("vmClient")
.Select(vmClient => (string) vmClient.Attribute("name"));
请注意我们如何测试VM
元素,而不是vmClients
元素。