Answer the question
In order to leave comments, you need to log in
How to implement counting the number of child nodes inside the parent node of some XML document?
Hello.
I load some XML document into the program: var xml = XDocument.Load(pathToXMLFile);
The content of this XML document looks like this:
<ROOT>
<data>
<record>
<field name="OID">51278ACDZF...</field>
<field name="Country or Area">AFGHANISTAN, I.R. OF</field>
<field name="Year">1989</field>
<field name="Description">TRADE BALANCE</field>
<field name="Magnitude">MILLIONS OF US$</field>
<field name="Value">-371200000</field>
</record>
<record>
<field name="OID">51278AEDZF...</field>
<field name="Country or Area">AFGHANISTAN, I.R. OF</field>
<field name="Year">1989</field>
<field name="Description">SERVICES: DEBIT</field>
<field name="Magnitude">MILLIONS OF US$</field>
<field name="Value">-103400000</field>
</record>
</data>
</ROOT>
<field>
are located inside the parent node <record>
. <record>
). But in different XML documents, this number will be different. <field>
within a node <record>
, in an XML document? <field>
within a node <record>
is constant. That is, if, for example, there are <record>
5 nodes in the first node <field>
, then there <record>
will be the same number of nodes in the remaining nodes of this XML document <field>
. int p = 0;
xml.XPathSelectElements("//record").ToList().ForEach(n =>
{
p = p + 1;
});
int q = 0;
xml.XPathSelectElements("//field").ToList().ForEach(n =>
{
q = q + 1;
});
int m = q / p;
//где m - требуемое число
Answer the question
In order to leave comments, you need to log in
Look towards LINQ TO XML.
XDocument xdoc = XDocument.Load(pathToXMLFile);
int countRecord = (from xe in xdoc.Root.Descendants("record") select xe).Count();
int countField = (from xe in xdoc.Root.Descendants("field") select xe).Count();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question