Java:如何使用stax从xml获取特定信息

问题描述 投票:0回答:1

我无法使用stax从我的xml获取特定信息。在我的xml内,我有一个当前值和平均值,这两个值中都有一个旅行时间。但是我只想从当前而不是从平均值中获得旅行时间。这是我的xml样子:

<allroutes>
    <routes>    
        <route identification="id_1">
            <current>
                <traveltime time="1187" trustworthy="j" />
                <delay time="0" trustworthy="j" />
            </current>
            <average>
                <traveltime time="1187" trustworthy="j" />
                <delay time="0" trustworthy="j" />
            </average>
        </route>
        <route identification="id_2">
            <current>
                <traveltime time="995" trustworthy="j" />
                <delay time="0" trustworthy="j" />
            </current>
            <average>
                <traveltime time="995" trustworthy="j" />
                <delay time="0" trustworthy="j" />
            </average>
        </route>
    </routes>
    <subpaths>
        <subpath identification="id_1">
            <current>
                <traveltime time="0" trustworthy="n" />
                <delay time="0" trustworthy="n" />
            </current>
            <average>
                <traveltime time="0" trustworthy="n" />
                <delay time="0" trustworthy="n" />
            </average>
        </subpath>
        <subpath identification="id_2">
            <current>
                <traveltime time="0" trustworthy="n" />
                <delay time="0" trustworthy="n" />
            </current>
            <average>
                <traveltime time="0" trustworthy="n" />
                <delay time="0" trustworthy="n" />
            </average>
        </subpath>
    </subpaths>
</allroutes>

我当前拥有的代码如下:

try{
    while (streamReader.hasNext()) {
        streamReader.next();
        if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT) {

            switch (streamReader.getLocalName()) {
            case "route":
                //store which type
                break;
            case "subpath":
                //store which type
                break;
            case "traveltime":
                //store traveltime
                break;
            }
        }

        if (streamReader.getEventType() == XMLStreamReader.END_ELEMENT && "allroutes".equals(streamReader.getLocalName())) {

            //stop the loop and give back the object
        }
    }
}catch(XMLStreamException ex) {
    LOGGER.log(Level.SEVERE, "XMLStreamException: " + ex);
}

我需要添加/更改什么才能仅从此阅读器中的“当前”获取旅行时间?

java xml stax
1个回答
1
投票

您只需要跟踪文档中的位置即可。例如,通常的做法是保留一堆元素名称:单击startElement时将名称推入堆栈,单击endElement时将其弹出,然后检查堆栈以发现当前正在处理的元素的上下文。

© www.soinside.com 2019 - 2024. All rights reserved.