How to get XML element path using stax/stax2?

删除回忆录丶 提交于 2019-12-12 04:25:52

问题


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.


回答1:


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;
            }
        }
    }
}



回答2:


"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.



来源:https://stackoverflow.com/questions/41108090/how-to-get-xml-element-path-using-stax-stax2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!