Java XML parse / query

I have this XML structure when I use NodeList nList = doc.getElementsByTagName ("stock"); he gives me back 3 stocks, 2 main stock tags and the one under the armrests. I only want to get the two stocks that are on the top level and ignore anything under the pad tags.

Is it possible in Java to do something like a LINQ query in C #, say, return me items only where the name is "Sony".


             <name>Panasonic Shop 2</name>



source to share

4 answers

I recommend that you use XPath with javax.xml. xpath :

final InputStream is = new FileInputStream('your.xml');

final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(is);
final XPathFactory xPathfactory = XPathFactory.newInstance();
final XPath xpath = xPathfactory.newXPath();
final XPathExpression expr = xpath.compile("/city/stock/name[text()='Sony']");


and then:

final NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);




Take a look at XPath and its java JXPath implementation . Another possible approach is to parse XML using JAXB and a list of work objects using LambdaJ.



There is also a dom4j library that has powerful navigation with XPath:

import org.dom4j.Document;

SAXReader reader = new SAXReader();
Document document ="test.xml");
List list = document.selectNodes("/city/stock/name[text()='Sony']");
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
    // TODO: place you logic here


More examples here



Try jcabi-xml (see this blog post ) with one layer:

Collection<XML> found = new XMLDocument("your document here").nodes(




All Articles