【发布时间】:2013-12-28 03:40:05
【问题描述】:
<?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 属性的所有值。例如,我想获取 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);
}
}
}
【问题讨论】:
-
您目前正在
vmClients元素中测试name属性 - 但name属性仅在vmClient(单数)或VM上。
标签: c# xml-parsing linq-to-xml