Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to get total number of child nodes of xml file and total elements in each child node.[i want to display the xml file in table layout control at run time for that i need to count rows and coloms]
how to get count of rows and colums at runtime based on xml file.
Posted

Parse the file with one of the XML classes available in .NET, such as https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx[^].
 
Share this answer
 
Have a look at example:
XML
//define xml document content
string xcontent = @"<?xml version='1.0' ?>
        <table>
        <rows>
        <row number='0'>
            <col number='1' header='true'>A</col>
            <col number='2' header='true'>B</col>
        </row>
        <row number='1'>
            <col number='1' header='false'>ValueA1</col>
            <col number='2' header='false'>ValueB1</col>
        </row>
        <row number='2'>
            <col number='1' header='false'>ValueA2</col>
            <col number='2' header='false'>ValueB2</col>
        </row>
        </rows>
        </table>";

//create xml document from string
XDocument xdoc = XDocument.Parse(xcontent);

//get the name of element, its level and no. of subnodes
var result = xdoc.Descendants()
        .Select(x=>new
            {
                NodeName = x.Name,
                NodeLevel = x.AncestorsAndSelf().Count(),
                ChildsCount = x.Descendants().Count()
            }
        )
        .Distinct();


Result:

NodeName NodeLevel ChildsCount
table    1         10
rows     2         9
row      3         2
col      4         0


You might be interested in other properties and methods of XmlElement class[^]. A most interesting is XElement.AncestorsAndSelf Method ()[^]
 
Share this answer
 
Comments
Matt T Heffron 1-Oct-15 19:03pm    
+5!
Cool
Maciej Los 1-Oct-15 19:07pm    
Thank you, Matt
BillWoodruff 1-Oct-15 19:41pm    
+5 Excellent !
Maciej Los 2-Oct-15 0:27am    
Thank you, Bill.
Member 12390137 2-Jun-16 4:23am    
Hello guys I have never use xml b4 how to use this on.

private void cmdCountUsingString_Click(object sender, EventArgs e)
{

}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900