简体   繁体   中英

How to get XML element path using stax/stax2?

I want to get element path while parsing XML using java StAX2 parser. How to get information about the current element path?

<root>
  <a><b>x</b></a>
</root>

In this example the path is /root/a/b .

Keep a stack. Push the element name on START_ELEMENT and pop it on END_ELEMENT.

Here's a short example. It does nothing other than print the path of the element being processed.

public static void main(String[] args) throws IOException, XMLStreamException {
    try (FileInputStream in = new FileInputStream("test.xml")) {

        XMLInputFactory factory = XMLInputFactory.newFactory();
        XMLStreamReader reader = factory.createXMLStreamReader(in);

        LinkedList<String> path = new LinkedList<>();

        int next;
        while ((next = reader.next()) != XMLStreamConstants.END_DOCUMENT) {
            switch (next) {
                case XMLStreamConstants.START_ELEMENT:
                    // push the name of the current element onto the stack
                    path.addLast(reader.getLocalName());
                    // print the path with '/' delimiters
                    System.out.println("Reading /" + String.join("/", path));
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    // pop the name of the element being closed
                    path.removeLast();
                    break;
            }
        }
    }
}

"The chronicler's duty"

Method 1: dedicated stack, @teppic suggestion

try (InputStream in = new ByteArrayInputStream(xml.getBytes())) {
    final XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory.newInstance();
    final XMLStreamReader2 reader = (XMLStreamReader2) factory.createXMLStreamReader(in);
    Stack<String> pathStack = new Stack<>();
    while (reader.hasNext()) {
        reader.next();
        if (reader.isStartElement()) {
            pathStack.push(reader.getLocalName());
            processPath('/' + String.join("/", pathStack));
        } else if (reader.isEndElement()) {
            pathStack.pop();
        }
    }
}

Method 2 (ugly): hacking Woodstox's InputElementStack

  • Implementing adapter to access InputElementStack , its protected mCurrElement and interate parents (this slows down algoritm).

     package com.ctc.wstx.sr; import java.util.LinkedList; public class StackUglyAdapter { public static String PATH_SEPARATOR = "/"; private InputElementStack stack; public StackUglyAdapter(InputElementStack stack) { this.stack = stack; } public String getCurrElementLocalName() { return this.stack.mCurrElement.mLocalName; } public String getCurrElementPath() { LinkedList<String> list = new LinkedList<String>(); Element el = this.stack.mCurrElement; while (el != null) { list.addFirst(el.mLocalName); el = el.mParent; } return PATH_SEPARATOR+String.join(PATH_SEPARATOR,list); } } 
  • example of use:

     try (final InputStream in = new ByteArrayInputStream(xml.getBytes())) { final XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory.newInstance(); final XMLStreamReader2 reader = (XMLStreamReader2) factory.createXMLStreamReader(in); final StackUglyAdapter stackAdapter = new StackUglyAdapter(((StreamReaderImpl) reader).getInputElementStack()); while (reader.hasNext()) { reader.next(); if (reader.isStartElement()) { processPath(stackAdapter.getCurrElementPath()); } } } 

Method 1 with dedicated stack is better, because is API implementation-independent and is just as fast as the Method 2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM