[英]Check if the node exist in XDocument
I have this xml: 我有这个xml:
<Rejectedparameters>
<parameter>
<name>CO</name>
<value>5.34</value>
</parameter>
<parameter>
<name>CO2</name>
<value>10.1</value>
</parameter>
<parameter>
<name>HC</name>
<value>473</value>
</parameter>
<parameter>
<name>O2</name>
<value>2</value>
</parameter>
</Rejectedparameters>
I need to check if for example a node exists - like this : 我需要检查例如是否存在节点-像这样:
int Gvalue = (from x in document.Elements("Rejectedparameters").Elements("parameter")
from p in x.Elements("Name")
where x.Element("CO").Value.ToString() != string.Empty
select x).Count();
but the Gvalue is 0 - why? 但是Gvalue是0-为什么? As you can see, the
CO
is exists in the XML. 如您所见,
CO
存在于XML中。
Firstly, each parameter
element only has a single name, so just use Element
for that. 首先,每个
parameter
元素只有一个名称,因此只需使用Element
。
Next, use name
as the element you're looking for, not Name
. 接下来,使用
name
作为您要查找的元素,而不是Name
。
Finally, you're looking for a value of CO
, not an element called CO
. 最后,您要查找的是
CO
的值 ,而不是名为CO
的元素 。 So you'd have something like: 所以你会有类似的东西:
var query = doc
.Root
.Elements("parameter")
.Where(parameter => (string) parameter.Element("name") == "CO" &&
!string.IsNullOrEmpty((string) parameter.Element("value"));
var count = query.Count(); // It's not clear why this was Gvalue in your original code
I've guessed at what you were trying to do with the check for an empty string... you may not need the second part of the filter. 我猜到您正在尝试检查空字符串...您可能不需要过滤器的第二部分。 I've assumed that you don't only want to get the count - that you actually want to use the elements too.
我假设您不仅想要获得计数-您实际上也想使用元素。
An alternative approach would be to convert all the parameters with a query first: 一种替代方法是首先使用查询转换所有参数:
var parameters = doc.Root.Elements("parameter").Select(p =>
new { Name = (string) p.Element("name"), Value = (string) p.Element("value") });
// Just as an example...
var co = parameters.SingleOrDefault(p => p.Name == "CO");
Firstly, the CO
is not element. 首先,
CO
不是元素。 It is value. 这是价值。 And you should change your query;
并且您应该更改查询;
var gValue = document.Descendants("name").Count(x => x.Value == "CO");
Output : 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.