2

I'm trying to create a new method to find elements into a XML, I'd like to create dinamic queries in a xml, I didn't find examples using xpath,

It's possible to use xpath with stax? If not, is there an easy way to create queries to find elements with stax?

public static void main(String[] args) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();

    Reader fileReader = new StringReader(ExempleXml.xml);
    XMLStreamReader reader = factory.createXMLStreamReader(fileReader);

    while (reader.hasNext()) {
        process(reader);
        reader.next();
    }

}

private static void process(XMLStreamReader reader) {
    int eventType = reader.getEventType();
    switch (eventType) {
        case XMLStreamConstants.START_ELEMENT:
            System.out.println("Start element: " + reader.getLocalName());

            int count = reader.getAttributeCount();
            for (int i = 0; i < count; i++) {
                String name = reader.getAttributeLocalName(i);
                String value = reader.getAttributeValue(i);
                System.out.println("\tAttribute name/value: " + name + "/" + value);
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            System.out.println("End element: " + reader.getLocalName());
            break;

        case XMLStreamConstants.CHARACTERS:
            System.out.println("Text: " + reader.getText());
            break;
        default:
            break;
    }
}
Lucas Pires
  • 1,281
  • 14
  • 21
  • 1
    XPath is intended to work on a Document Object Model (DOM), and thus not with a streaming approach. Apparently someone has put together a library to shoehorn XPath into a streaming model, but I'm dubious about putting reins on a bicycle. Why use a streaming model if you want to manipulate a DOM? – Lew Bloch May 18 '17 at 16:28
  • 1
    I think this blog post is very similar to what you are asking http://stackoverflow.com/questions/8791600/can-sax-parsers-use-xpath-in-java – vtd-xml-author May 18 '17 at 20:13

1 Answers1

1

For the limited xpath support on top of the StaX parser you can use https://github.com/polyglotted/xpath-stax