user4437794
user4437794

Reputation:

Counting number of element in xml file

First of all I referred this post How to get specific element Count in XML or XElement variable and could not solve the problem which i was facing so i am writing this. The part of the xml is given as below I want to count the number of element that is number of occurance scalarvariable in modelvariables node as shown below

<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>

I have defined as

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

and i have created nodelist as

XmlNodeList nodeList = (XmlNodeList)doc.DocumentElement.SelectNodes("//ModelVariables/ScalarVariable");

I need to get the number of occurnace of the scalarvariable

Upvotes: 0

Views: 8245

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21825

You need Count here:-

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

Upvotes: 3

Related Questions