get the number of children of a given element

M

Matt

I want to get the number of children of a given element. Below is my
code attempt and
the xml sample file. The caller is getElementChildNumber("persons");,
I expect
to get 2. Since there are 2 children that are under persons element.
Any ideas??

/**
get the number of children of a given element
*/
public int getElementChildNumber(String elementName)
{
DocumentBuilderFactory dbf = null;
DocumentBuilder db = null;
Document doc = null;
try
{
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(fileName);
NodeList nodelist = doc.getElementsByTagName(elementName);
return nodelist.getLength();
}
catch (Exception e)
{ e.printStackTrace();
}
return -1;
}

<?xml version="1.0" encoding="UTF-8"?>
<response>
<persons>
<person>
<name>Joe</name>
<age>10</age>
</person>
<person>
<name>Mark</name>
<age>30</age>
</person>
</persons>
</response>
 
A

Andy Fish

reading the manual, it says that getElementsByTagName will return a list of
all the elements of that tag name. since you have one 'persons' element, I
would expect your function to return 1.

if you want to count the number of children under a given element, call
getChildNodes() on it.

note that this will probably also return some whitespace nodes, so you might
have to filter through the list if you only want to count the elements
 
M

mromarkhan

Peace.
Here is an xpath solution for the casual onlooker.
Tested on Mozilla.org Firefox and Microsoft Internet Explorer
returns
Node Count for Person:4
Node Count for Name:4
Node Count for Age:2


count.xml count.xsl

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="count.xsl"?>
<response>
<persons>
<person>
<name>Joe</name>
<age>10</age>
</person>
<person>
<name>Mark</name>
<age>30</age>
</person>
<person>
<name>Khan</name>
</person>
<person>
<name>Omar</name>
</person>
</persons>
</response>


<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="person" select="count(/response/persons/person)" />
<xsl:variable name="name" select="count(/descendant::name)" />
<xsl:variable name="age" select="count(/descendant::age)" />
<xsl:template match="/">
<html>
<body>
Node Count for Person:<xsl:copy-of select="$person" /> <br />
Node Count for Name:<xsl:copy-of select="$name" /> <br />
Node Count for Age:<xsl:copy-of select="$age" /> <br />
<br />
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Have a good day.

-- References
<[email protected]>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top