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>
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>