2012-08-04 284 views
0

我正在Java代碼中進行web服務調用,並將響應作爲字符串與以下數據一起獲取。從Java中的webservice響應中解析CDATA內容

<DocumentElement> 
    <ResultSet> 
    <Response>Successfully Sent.</Response> 
    <UsedCredits>1</UsedCredits> 
    </ResultSet> 
</DocumentElement> 

現在,我想分析下面的響應字符串並獨自一人的<Response>變量的值進行進一步的處理。因爲,我只能獲取如何解析String內容的CDATA內容?

+0

@mzjn上面給出的數據包含在CDATA部分中。 – 2012-08-04 07:01:21

回答

0

你明顯需要這個XML解析器。比方說,上述被存儲在一個名爲content

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    try { 
      //Using factory get an instance of document builder 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      InputSource is = new InputSource(); 
      is.setCharacterStream(new StringReader(content)); //content variable holding xml records   
      Document doc = db.parse(is) 
      /* Now retrieve data from xml */ 
      NodeList nodes = doc.getElementsByTagName("ResultSet"); 
      Element elm = (Element) nodes.item(0); //will get you <Response> Successfully Sent.</Response> 
      String responseText = elm.getFirstChild().getNodeValue(); 

    }catch(ParserConfigurationException pce) { 
     pce.printStackTrace(); 
    }catch(SAXException se) { 
     se.printStackTrace(); 
    }catch(IOException ioe) { 
     ioe.printStackTrace(); 
    } 

按照上面的解析器例程更大的數據集的String變量。對多個相似的數據集使用循環。希望有所幫助。

+0

另外,既然你是一個新用戶,如果你覺得它有幫助,不要忘記勾選這個答案左邊的箭頭。 – jmishra 2012-08-04 06:34:55

+0

我在哪裏可以找到'getCharacterDataFromElement'方法的代碼? – 2012-08-04 07:00:48

+0

對不起,我的道歉。我忘了包括這一點。我的答案現在已更新。 – jmishra 2012-08-04 07:10:16