Using XPath - beckchr/staxon GitHub Wiki

XPath is another standard that can be easily adopted for use with JSON.

The Java XPath API (javax.xml.xpath) doesn't let us provide an XMLStreamReader or similar as a source, but requires a Document Object Model (DOM). Therefore, we need to read our JSON into a DOM first to apply expressions against that DOM. This could be done by performing an XSLT identity transformation to a DOMResult. However, StAXON provides the DOMEventConsumer class to translate XML events to DOM nodes, which should be faster and simpler than leveraging XSLT.

Once we have a DOM, there's nothing special with applying XPath expressions.

import java.io.StringReader;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.util.DOMEventConsumer;

public class XPathDemo {
	public static void main(String[] args) throws XMLStreamException, XPathException {
		StringReader json = new StringReader("{\"edgar\":\"david\",\"bob\":\"charlie\"}");
		
		/*
		 * Our sample JSON has no root element, so specify "alice" as virtual root
		 */
		JsonXMLConfig config = new JsonXMLConfigBuilder().virtualRoot("alice").build();

		/*
		 * create event reader
		 */
		XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(json);

		/*
		 * parse JSON into Document Object Model (DOM)
		 */
		Document document = DOMEventConsumer.consume(reader);

		/*
		 * evaluate an XPath expression
		 */
		XPath xpath = XPathFactory.newInstance().newXPath();
		System.out.println(xpath.evaluate("//alice/bob", document));
	}
}

Running the above sample will print charlie to the console.