Skip to main content

Java/XML: Counting elements based on parent element's attribute value...

1 reply [Last post]
Joined: 2010-10-08
Points: 0

I am developing a Java application to, among other things, extract the
number of child elements based on an attribute value of the parent
element. For example, if I have the following XML:



and I run the program as

java MyProg type1

I want the number "2" returned since there are 2 elements
under . Likewise if I run as

java MyProg type2

I want the number "3" returned. This seems like such a simple
task but I have been unable to restrict the XML parsing to just
one "branch" of the file. When I run my version of the program
the number "5" is always returned. In other words the parser
(DOMParser) is returning the total number of ALL
elements, NOT just the ones within a specific parent

Thanks in advance for any help!


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2006-09-06
Points: 0

Hold on ... [i]copy, paste, snip, snip, snip[/i] ... ta da:


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class MyProg {

private static XPathFactory xPathFactory = XPathFactory.newInstance();
private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory

public static void main(String[] args) throws ParserConfigurationException,
IOException, SAXException, XPathExpressionException {
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(;
Node root = document.getDocumentElement();
XPath xPath = xPathFactory.newXPath();
Number count = (Number)xPath.evaluate("count(/db/pattern[@type='" + args[0] + "']/bm)", root,

Of course the formatting is going to be all trampled - nevermind.

For XPath functions find a useful reference here: