C# 在XML中使用If、Then、Else on条件

C# 在XML中使用If、Then、Else on条件,c#,xml,vb.net,if-statement,C#,Xml,Vb.net,If Statement,只有当条件为真时,谁能帮助处理字段中的信息 我已经试过了,但我想要更优雅的 <?xml version="1.0" encoding="UTF-8" ?> <root> <Events> <Event Id="1"> <Condition>True</Condition> <Fields> <Parameter Name="thisOne"

只有当
条件
时,谁能帮助处理字段中的信息

我已经试过了,但我想要更优雅的

<?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>

真的
假的

使用
Where
子句将LINQ中的数据集限制为XML

您可以通过深入元素并调用
.value

这将加载作为事件一部分的所有每个参数的所有名称和值,该事件具有值为True的condition元素:

Dim xdoc As XDocument=XDocument.Parse(str)
Dim参数=xdoc.Root.Elements(“事件”).Elements(“事件”)中的e
来自e.Elements(“字段”).Elements(“参数”)中的p
其中e.Element(“条件”).Value=“True”
选择“新建”{
.Name=p.Attribute(“Name”).Value,
.Value=p.Attribute(“Value”).Value
}
这应该可以做到:

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")
                                 }));
这将为每个
事件
元素选择一组参数,其中
条件
。换句话说,
paramSets
的类型是
IEnumerable
,其中
T
是一个匿名类型,具有
名称
属性

您可以这样循环:

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);
    }
}

您使用什么工具来解析xml?林克?XMLT?XPath?现在是LINQ,但可以接受建议谢谢Kyle和JL。好东西!