计算具有属性值的节点
count nodes with attribute value
我正在尝试从 XmlDocument 切换到 Linq,并且正在努力获得我想要的东西。
我有XML类似的,
<root>
<Surfer Status='5'>
<Name>Billy</Name>
<County>Cornwall</County>
</Surfer>
<Surfer Status='5'>
<Name>Tim</Name>
<County>Cornwall</County>
</Surfer>
<Surfer Status='10'>
<Name>Ryan</Name>
<County>Devon</County>
</Surfer>
</root>
我可以这样数所有的冲浪者
XDocument X = XDocument.Load("Surfers.xml");
int Total = X.Descendants("Surfer").Count();
我希望像这样统计所有状态为 5 的冲浪者
int fives = X.Descendants["Surfer[@Status='5']").Count();
但是没用!
使用Where
:
int fives = X.Descendants("Surfer").Where(s => (int)s.Attribute("Status") == 5).Count();
或者如果你真的想使用 XPath 表达式,你可以在添加 using System.Xml.XPath
并使用 XPathSelectElements
:
int fives = X.XPathSelectElements("Surfer[@Status='5']").Count();
您可以使用带有谓词的 Count
重载
int fives = X.Descendants("Surfer").Count(x => x.Attribute("Status")?.Value == "5");
x.Attribute("Status")
将从 Surfer
元素中检索 Status
属性,并且 ?.
运算符会阻止 NullReferenceException
如果任何 Surfer
元素检索没有 Status
属性。
我正在尝试从 XmlDocument 切换到 Linq,并且正在努力获得我想要的东西。
我有XML类似的,
<root>
<Surfer Status='5'>
<Name>Billy</Name>
<County>Cornwall</County>
</Surfer>
<Surfer Status='5'>
<Name>Tim</Name>
<County>Cornwall</County>
</Surfer>
<Surfer Status='10'>
<Name>Ryan</Name>
<County>Devon</County>
</Surfer>
</root>
我可以这样数所有的冲浪者
XDocument X = XDocument.Load("Surfers.xml");
int Total = X.Descendants("Surfer").Count();
我希望像这样统计所有状态为 5 的冲浪者
int fives = X.Descendants["Surfer[@Status='5']").Count();
但是没用!
使用Where
:
int fives = X.Descendants("Surfer").Where(s => (int)s.Attribute("Status") == 5).Count();
或者如果你真的想使用 XPath 表达式,你可以在添加 using System.Xml.XPath
并使用 XPathSelectElements
:
int fives = X.XPathSelectElements("Surfer[@Status='5']").Count();
您可以使用带有谓词的 Count
重载
int fives = X.Descendants("Surfer").Count(x => x.Attribute("Status")?.Value == "5");
x.Attribute("Status")
将从 Surfer
元素中检索 Status
属性,并且 ?.
运算符会阻止 NullReferenceException
如果任何 Surfer
元素检索没有 Status
属性。