all groups > dotnet xml > november 2006 >
You're in the

dotnet xml

group:

How to access the total number of child nodes from a parent node


How to access the total number of child nodes from a parent node MA
11/27/2006 9:21:51 PM
dotnet xml:
Hi,

How to access the total number of child nodes from a parent node. For
example, I would like to get the total number of child nodes from
<parent1> and <parent2> node. The SelectNodes method return the total
number of <folder> nodes (9) regardless of calling from the <parent1>
and <parent2> node.

XML:
----------------------------------
<Mailbox DisplayName="test">
<parent1>
<folders>
<folder name="test001">
<folder name="test001"/>
<folder name="test003">
<folder name="test004">
<folder name="test005"/>
<folder name="test006"/>
</folder>
</folder>
</primary>

<parent2>
<folders>
<folder name="test007">
<folder name="test008">
<folder name="test009">
</folders>
</archive>
</Mailbox>
----------------------------------

My C# code return 9 childs for each execution. Correct result will be 6
for <parent1> and 3 for the <parent2> child node. Here is the code:
----------------------------------
// node = Mailbox node

foreach (XmlNode childNode in node.ChildNodes)
{
XmlNodeList folders = childNode.SelectNodes("//folder");
int total = folders.Count; <---- return 9.
}

----------------------------------

Thanks in advance.

- MA
Re: How to access the total number of child nodes from a parent node MA
11/27/2006 9:24:56 PM
Please ignore the typo of the end tag </archive> and </primary>. Thanks
in advance.
Re: How to access the total number of child nodes from a parent node Patrick.O.Ige
11/28/2006 12:00:00 AM
XmlNodeList folders = childNode.SelectNodes("//folder");
MA have u tried childNode.SelectNodes("/Parent/folder"); and
childNode.SelectNodes("/Parent2/folder");
Patrick


[quoted text, click to view]

Re: How to access the total number of child nodes from a parent node Martin Honnen
11/28/2006 2:29:40 PM
[quoted text, click to view]

You need a relative XPath expression e.g.
childNode.SelectNodes("folder")
for all |folder| element child nodes or
childNode.SelectNodes(".//folder")
for all |folder| element descendant nodes.

If you have an XPath expression starting with / then it is always an
absolute XPath expression starting from the root node so it does not
help with SelectNodes/SelectSingleNode if you want to look at nodes
relative to the node you call the method on.




--

Martin Honnen --- MVP XML
Re: How to access the total number of child nodes from a parent node MA
11/28/2006 3:02:41 PM
Thanks "Martin", its working as expected.

Cheers,
MA
AddThis Social Bookmark Button