[英]Using If, Then, Else on Condition in XML
只有在Condition
为True
时,任何人都可以帮助您处理字段中的信息吗?
我已经尝试了For Each,如果可以的话,但是我想要更优雅的方法。
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<Events>
<Event Id="1">
<Condition>True</Condition>
<Fields>
<Parameter Name="thisOne" Value="1234" />
<Parameter Name="notthisOne" Value="xyz" />
<Parameter Name="thisoneagain" Value="5678" />
<Parameter Name="notthisoneAgain" Value="abc" />
</Fields>
</Event>
<Event Id="2">
<Condition>False</Condition>
<Fields>
<Parameter Name="thisOne" Value="1234" />
<Parameter Name="notthisOne" Value="xyz" />
<Parameter Name="thisoneagain" Value="5678" />
<Parameter Name="notthisoneAgain" Value="abc" />
</Fields>
</Event>
</Events>
</root>
应该这样做:
var paramSets = e.Descendants("Event")
.Where(ev => (string)ev.Element("Condition") == "True")
.Select(ev => ev.Descendants("Parameter")
.Select(p => new
{
Name = (string)p.Attribute("Name"),
Value = (string)p.Attribute("Value")
}));
这将为Condition
为True
每个Event
元素选择一组参数。 换句话说, paramSets
的类型是IEnumerable<IEnumerable<T>>
,其中T
是具有Name
and Value
属性的匿名类型。
您可以像这样循环遍历:
foreach (var event in paramSets)
{
foreach (var parameter in event)
{
// Do something with the parameter
Console.WriteLine("Name: {0}, Value: {1}", parameter.Name, parameter.Value);
}
}
使用Where
子句将LINQ中的数据集限制为XML。
您可以通过深入到某个元素并调用.Value
来获取特定元素的值。
这将为Event的所有每个参数加载所有名称和值,Event的条件元素的值为True:
Dim xdoc As XDocument = XDocument.Parse(str)
Dim parameters = From e In xdoc.Root.Elements("Events").Elements("Event")
From p In e.Elements("Fields").Elements("Parameter")
Where e.Element("Condition").Value = "True"
Select New With {
.Name = p.Attribute("Name").Value,
.Value = p.Attribute("Value").Value
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.