A
A
Alexey Smirnov2016-02-28 14:43:43
.NET
Alexey Smirnov, 2016-02-28 14:43:43

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>

I need to count how many nodes <field>are located inside the parent node <record>.
In this example, there are 6 of them (in each node <record>). But in different XML documents, this number will be different.
How to implement counting the number of nodes <field>within a node <record>, in an XML document?
PS Within a single XML document, the number of nodes <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>.
P.S. I use this method:
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 - требуемое число

and this method calculates everything correctly, but I think that this method overloads the processor unnecessarily (since the XML document is completely "read" 2 times).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
V Sh., 2016-02-29
@ERAFY

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

I can't speak for speed, but it should be better.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question