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".
Thank!
<city>
<stock>
<name>Sony</name>
</stock>
<stock>
<name>Panasonic</name>
<substocks>
<stock>
<name>Panasonic Shop 2</name>
</stock>
</substocks>
</stock>
</city>
+3
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);
+3
source to share
There is also a dom4j library that has powerful navigation with XPath:
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
SAXReader reader = new SAXReader();
Document document = reader.read("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
+1
source to share