检查节点是否存在于XDocument中

时间:2017-12-25 13:57:32

标签: c# 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>

我需要检查一个节点是否存在 - 如下所示:

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

但是Gvalue是0 - 为什么?如您所见,CO存在于XML中。

2 个答案:

答案 0 :(得分:9)

首先,每个Public MustInherit Class ProbSts 'class X Public Status As Boolean Public Probability, Min, Max As Integer End Class Public NotInheritable Class SIPRouteProbabilityStatus 'class A Inherits ProbSts Public Route As SIPRoute End Class Public NotInheritable Class SIPRGProbabilityStatus ' class C Inherits ProbSts Public RG As SIPRouteGroup End Class Public NotInheritable Class SIPRouteProbabilityStatusCollection ' class B Inherits List(Of SIPRouteProbabilityStatus) Public ProbabilityTotal As Integer Public Function TotalProbability(Optional Status As Boolean? = Nothing) As Integer Return TotalProbabilityAction(Me, Status) End Function End Class Public NotInheritable Class SIPRGProbabilityStatusCollection 'class D Inherits List(Of SIPRGProbabilityStatus) Public ProbabilityTotal As Integer Public Function TotalProbability(Optional Status As Boolean? = Nothing) As Integer Return TotalProbabilityAction(Me, Status) End Function End Class Friend Module ProbabilityAction Public Function TotalProbabilityAction(ProbStsList As IEnumerable(Of ProbSts), Optional Status As Boolean? = Nothing) As Integer Dim sum As Integer = 0 For Each x In ProbStsList If Status.HasValue Then If x.Status = Status.Value Then sum += x.Probability Else sum += x.Probability End If Next Return sum End Function End Module 元素只有一个名称,因此只需使用parameter即可。

接下来,使用Element作为您要查找的元素,而不是name

最后,您正在寻找Name,而不是名为CO元素。所以你有类似的东西:

CO

我已经猜到了你要检查空字符串的方法......你可能不需要过滤器的第二部分。我假设你不想要计算 - 你实际上也想要使用这些元素。

另一种方法是首先使用查询转换所有参数:

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

答案 1 :(得分:1)

首先,$ npm install --save prop-types 不是元素。这是价值。你应该改变你的查询;

CO