2014-09-13 57 views
0

嗨,Stax解析不會返回正確的響應

我在使用Jaxb解析SOAP響應時遇到了很奇怪的問題。我無法在解析時獲取完整的標籤列表.Stax解析器只能解析一個標籤,它不會給出任何錯誤或異常。但是,如果我嘗試格式化xml響應(存儲在字符串中),那麼一切正常精細。下面是我在做什麼解析它: -

public void parseResponse(){ 
    String response="<SOAP:Body><response><result><myTag></myTag><myTag></myTag>/result</response</SOAP:Body>"; 

    getUnmarshalledObject(response,myTag,MyTag.class,"com.mylearning.parseXml"); 
    } 





    public <T> List<T> getUnmarshalledObject(String response ,String TAG_TO_SEARCH ,Class<T> clazz , String basePkg) 
            throws XMLStreamException, JAXBException{ 
          Reader reader = new StringReader(response); 
          XMLInputFactory xif = XMLInputFactory.newInstance(); 
          XMLStreamReader xsr = xif.createXMLStreamReader(reader); 

          List<T> listOfUnmarshalledObjects = new ArrayList<T>(); 
          while (xsr.hasNext()) { 
           if (xsr.getEventType() == XMLStreamReader.START_ELEMENT && TAG_TO_SEARCH.equals(xsr.getLocalName())) { 
             T unmarshalledObj = unmarshalXml(clazz ,xsr, basePkg); 
             listOfUnmarshalledObjects .add(unmarshalledObj); 
            } 
            xsr.next(); 
           } 
          return listOfUnmarshalledObjects; 
         } 

以下是問題的不同的使用情況: -

  Case 1:- Input String response is unformatted. 
      Result :- listOfUnmarshalledObjects is 1. 

      Case 2:- Format response with response.replaceAll("><",">\n<"); 
      Result:- listOfUnmarshalledObjects is 2. 

      Case 3 : Input String unformatted , just give space b/w </myTag><myTag> 
      Result: listOfUnmarshalledObjects is 2. 

      I tried my best to explain the question, please help me.      
      > Blockquote 

回答

0

我原來,罪魁禍首是缺少其他條件。 解析遊標能夠找到..tag的第一個塊,但一旦完成它,xsr.next也會在每次迭代中執行。

所以在情況下XML沒有格式化: - 1.分析器找到的第一個完整的塊,並將其存儲在列表中,現在光標在接下來的標籤,但控制進入下一個迭代之前xsr.next被執行和將光標移動到下一個立即標記。

在格式化的XML的情況下: - 1.將有\之間的兩個連續塊\ n字符Ñ所以即使xsr.next得到在每次迭代執行 它只會吃\ n字符和光標將是正確的有望解析下一塊標籤。

下面是其他情況更新的代碼: -

while (xsr.hasNext()) { 
    if (xsr.getEventType() == XMLStreamReader.START_ELEMENT && TAG_TO_SEARCH.equals(xsr.getLocalName())) { 
      T unmarshalledObj = unmarshalXml(clazz ,xsr, basePkg); 
      listOfUnmarshalledObjects .add(unmarshalledObj); 
     }else{ 
      xsr.next(); 
      } 
    }