簡體   English   中英

Java:如何使用 stax 從 xml 中獲取特定信息

[英]Java: How to get specific information from xml using stax

我無法使用 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);
}

我需要添加/更改什么才能僅從該閱讀器中的“當前”獲取旅行時間?

您只需要跟蹤您在文檔中的位置。 例如,通常的做法是保留一個元素名稱堆棧:當您點擊 startElement 時將名稱壓入堆棧,當您點擊 endElement 時將其彈出,然后檢查堆棧以發現您當前正在處理的元素的上下文.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM