Goofy
Goofy

Reputation: 6128

How to count the number of children of a node in an XML document in Java?

I have xml similar to this:

<parent>
   <child1>
   <child2>
   <child3>
</parent>

Now there are 3 children for parent tag.So i need to get number of childern in parent tag.

I am using the following code but it is not working:

NodeList nodeList = doc.getElementsByTagName("a"); nodeList.getChildnodes();

How to do this please?

Upvotes: 2

Views: 12675

Answers (3)

Mihai Ilie
Mihai Ilie

Reputation: 38

Document doc = docBuilder.parse("YOUR_FILE_PATH");
Node tag1 = doc.getElementsByTagName("YOUR_NODE");
NodeList list1=tag1.getChildNodes();
         System.out.println(list1.getLength());

Make sure you import org.w3c.dom.* and javax.xml.*

Upvotes: 1

Goofy
Goofy

Reputation: 6128

no matter guys i got it thanks for your comments

NodeList image = doc.getElementsByTagName("Point");
Node singleTerminalNode = image.item(i);
Element firstLevel = (Element)singleTerminalNode;
NodeList value1Nodes = (firstLevel).getElementsByTagName("ImageFile");
int lengthofimage = value1Nodes.getLength();

Upvotes: 4

Pavel Ryzhov
Pavel Ryzhov

Reputation: 5152

File file = new File(new File(".").getPath() + "\\src\\yourFile.xml");
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
int childrenCount = doc.getChildNodes().item(0).getChildNodes().getLength();

Upvotes: 2

Related Questions