[英]Conditional LINQ query on XML file
我希望对在XML文件上执行的LINQ查询提供一些帮助。 我无法在搜索中找到适用于我的情况的任何内容,但我不得不承认我仍在尝试弄清LINQ。 因此,如果这是重复的话,我事先表示歉意,而我却忽略了一些事情。
我有一个在应用程序启动时创建并填充的XML文件。 我正在搜索此XML文件,并尝试仅列出给定主机名的在“ Citrix”下找到的所有“ Connection”元素。
因此,例如,给定以下XML文件,我只想返回
如果选择了“ client2”,则为“ desktop3”和“ desktop4”。
XML文件示例:
<ThinClients>
<ThinClient>
<Status>OK</Status>
<Hostname>client1</Hostname>
<Citrix>
<Connection>
<ConnectionName>desktop1</ConnectionName>
<XendesktopIP>192.168.0.10</XendesktopIP>
</Connection>
<Connection>
<ConnectionName>desktop2</ConnectionName>
<XendesktopIP>192.168.0.20</XendesktopIP>
</Connection>
</Citrix>
<ThinClient>
<ThinClient>
<Status>OK</Status>
<Hostname>client2</Hostname>
<Citrix>
<Connection>
<ConnectionName>desktop3</ConnectionName>
<XendesktopIP>192.168.0.30</XendesktopIP>
</Connection>
<Connection>
<ConnectionName>desktop4</ConnectionName>
<XendesktopIP>192.168.0.40</XendesktopIP>
</Connection>
</Citrix>
<ThinClient>
<ThinClients>
我可以获取所有ThinClient上所有Citrix连接的列表,但是我正努力只获取用于指定主机名的连接。
以下内容返回了所有主机的所有Citrix连接,但是由于主机名位于XML链的上游,因此我无法理解如何进一步扩展它并将其仅与主机名隔离。
public ObservableCollection<CitrixConnections> GetCitrixConnectionListByHostname(string Hostname)
{
IEnumerable<CitrixConnections> clients =
(from client in _Document.Elements("ThinClient").Elements("Citrix").Elements("Connection")
select new CitrixConnections
{
ConnectionName = client.Element("ConnectionName").Value,
XendesktopIP = client.Element("XendesktopIP").Value,
});
var clientsAsObservableCollection = new ObservableCollection<CitrixConnections>(clients);
return clientsAsObservableCollection;
}
这应该给您您想要的:
_Document
.Root
.Elements("ThinClient")
.Where(x => (string) x.Element("Hostname") == somevalue)
.SelectMany(x => x.Descendants("Connection"))
.Select(x => new CitrixConnections
{
ConnectionName = (string) x.Element("ConnectionName"),
XendesktopIP = (string)x.Element("XendesktopIP")
});
Document.Elements(“ ThinClient”)。Where(e => e.Element(“ Hostname”)。Value == hostname)。剩余代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.