C# 确定子元素之一是否在 XElement 中具有特定值
C# determine if one of child elements has specific value in XElement
请考虑这个XML
:
<MyRoot>
<c1>0</c1>
<c2>0</c2>
<c3>0</c3>
<c4>0</c4>
<c5>1</c5>
<c6>0</c6>
<c7>0</c7>
<c8>0</c8>
</MyRoot>
我如何编写一个 lambda 表达式来查找 MyRoot
的子项之一的值是否为 1?
谢谢
使用 XDocument
class 和一些 linq 是非常简单的:
string xml=@"<MyRoot>
<c1>0</c1>
<c2>0</c2>
<c3>0</c3>
<c4>0</c4>
<c5>1</c5>
<c6>0</c6>
<c7>0</c7>
<c8>0</c8>
</MyRoot>";
XDocument Doc = XDocument.Parse(xml);
var nodes = from response in Doc.Descendants()
where response.Value == "1"
select new {Name = response.Name, Value = response.Value };
foreach(var node in nodes)
Console.WriteLine(node.Name + ": " + node.Value);
See the working DEMO Fiddle as example
使用 lambda:
var nodes = Doc.Descendants().Where(x=> x.Value == "1")
.Select(x=> {Name = x.Name, Value = x.Value });
现在您可以对其进行迭代:
foreach(var node in nodes)
Console.WriteLine(node.Name + ": " + node.Value);
对于 VB 想要答案的人
Dim xe As XElement
'xe = XElement.Load("URI here")
'for testing use literals
xe = <MyRoot>
<c1>0</c1>
<c2>0</c2>
<c3>0</c3>
<c4>0</c4>
<c5>1</c5>
<c6>0</c6>
<c7>0</c7>
<c8>0</c8>
</MyRoot>
'any child = 1
Dim ie As IEnumerable(Of XElement) = From el In xe.Elements Where el.Value = "1" Select el
'check c4 for 1
ie = From el In xe.<c4> Where el.Value = "1" Select el
'or
If xe.<c4>.Value = "1" Then
'
End If
string x = @"<MyRoot>
<c1>0</c1>
<c2>0</c2>
<c3>0</c3>
<c4>0</c4>
<c5>1</c5>
<c6>0</c6>
<c7>0</c7>
<c8>0</c8>
</MyRoot>";
XElement xml = XElement.Parse(x);
bool has_one = xml.Elements().Any(z => z.Value == "1");
请考虑这个XML
:
<MyRoot>
<c1>0</c1>
<c2>0</c2>
<c3>0</c3>
<c4>0</c4>
<c5>1</c5>
<c6>0</c6>
<c7>0</c7>
<c8>0</c8>
</MyRoot>
我如何编写一个 lambda 表达式来查找 MyRoot
的子项之一的值是否为 1?
谢谢
使用 XDocument
class 和一些 linq 是非常简单的:
string xml=@"<MyRoot>
<c1>0</c1>
<c2>0</c2>
<c3>0</c3>
<c4>0</c4>
<c5>1</c5>
<c6>0</c6>
<c7>0</c7>
<c8>0</c8>
</MyRoot>";
XDocument Doc = XDocument.Parse(xml);
var nodes = from response in Doc.Descendants()
where response.Value == "1"
select new {Name = response.Name, Value = response.Value };
foreach(var node in nodes)
Console.WriteLine(node.Name + ": " + node.Value);
See the working DEMO Fiddle as example
使用 lambda:
var nodes = Doc.Descendants().Where(x=> x.Value == "1")
.Select(x=> {Name = x.Name, Value = x.Value });
现在您可以对其进行迭代:
foreach(var node in nodes)
Console.WriteLine(node.Name + ": " + node.Value);
对于 VB 想要答案的人
Dim xe As XElement
'xe = XElement.Load("URI here")
'for testing use literals
xe = <MyRoot>
<c1>0</c1>
<c2>0</c2>
<c3>0</c3>
<c4>0</c4>
<c5>1</c5>
<c6>0</c6>
<c7>0</c7>
<c8>0</c8>
</MyRoot>
'any child = 1
Dim ie As IEnumerable(Of XElement) = From el In xe.Elements Where el.Value = "1" Select el
'check c4 for 1
ie = From el In xe.<c4> Where el.Value = "1" Select el
'or
If xe.<c4>.Value = "1" Then
'
End If
string x = @"<MyRoot>
<c1>0</c1>
<c2>0</c2>
<c3>0</c3>
<c4>0</c4>
<c5>1</c5>
<c6>0</c6>
<c7>0</c7>
<c8>0</c8>
</MyRoot>";
XElement xml = XElement.Parse(x);
bool has_one = xml.Elements().Any(z => z.Value == "1");