2017-01-07 52 views
0

我正在尋找一種方法來停止解析器,一旦我得到我的標記內容。我怎樣才能做到這一點?另外我怎麼知道現在我打了我的標籤,我正在尋找。停止stax分析器執行

public class XmlParser { 

    public String getValue(final String xml, final String tag) throws XMLStreamException { 

    String tagContent = null; 

    final XMLInputFactory factory = XMLInputFactory.newInstance(); 
    final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(xml)); 

    while (reader.hasNext()) { 
     final int event = reader.next(); 
     switch (event) { 
     case XMLStreamConstants.START_ELEMENT: 
      break; 
     case XMLStreamConstants.CHARACTERS: 
      tagContent = reader.getText().trim(); 
      break; 
     case XMLStreamConstants.END_ELEMENT: 
      break; 
     } 
    } 
    return tagContent; 
    } 
} 

回答

1
boolean finished = false; 
while(!finished && reader.hasNext()) { 
    final int event = reader.next(); 
    //set finished = true if you hit an event that means you want to stop parsing 
} 
//don't forget to close the reader and the I/O streams 
+0

我想可能是有一個從Stax的API停止。 :) –

+0

當您不再需要繼續解析時,您只需關閉XML流或事件閱讀器。 –