计算xml文件中的元素数量

时间:2015-08-21 13:47:04

标签: c# xml linq xpath

首先,我提到这篇文章How to get specific element Count in XML or XElement variable并无法解决我所面临的问题所以我写这篇文章。 xml的部分如下所示我想计算在modelvariables节点中出现scalar变量数的元素数,如下所示

<ModelVariables>
 <ScalarVariable name="x" valueReference="0" description="the only state"causality="local" variability="continuous" initial="exact">
    <Real start="1"/>
 </ScalarVariable>
 <ScalarVariable name="der(x)" valueReference="1" causality="local" variability="continuous"        initial="calculated">
    <Real derivative="1"/>
 </ScalarVariable>
 <ScalarVariable name="k" valueReference="2" causality="parameter" variability="fixed" initial="exact">
    <Real start="1"/>
 </ScalarVariable>
</ModelVariables>

我定义为

  

XmlDocument doc = new XmlDocument();               doc.Load(@&#34; W:\ Prajwal \ FMU_EXTRACT \ modelDescription.xml&#34);

我已将节点列表创建为

  

XmlNodeList nodeList =   (XmlNodeList中)doc.DocumentElement.SelectNodes(&#34; // ModelVariables / ScalarVariable&#34);

我需要获得标量变量

的出现次数

1 个答案:

答案 0 :(得分:3)

您需要Count: -

XDocument doc = XDocument.Load(@"W:\Prajwal\FMU_EXTRACT\modelDescription.xml");
int ScalarVariableCount = doc.Root.Element("ModelVariables")
                                  .Elements("ScalarVariable").Count();