Skip to main content

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

1 reply [Last post]
aezekielian
Offline
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:

test1
test2

test1
test2
test3

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
type-value.

Thanks in advance for any help!

--abe

Reply viewing options

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

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

-----------------------------------------------------------
import java.io.IOException;

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
.newInstance();

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

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

For XPath functions find a useful reference here: http://www.w3schools.com/xpath/xpath_functions.asp