[英]Parsing CDATA content from webservice response in Java
我正在用Java代碼進行Web服務調用,並使用以下數據將響應作為String進行獲取。
<DocumentElement>
<ResultSet>
<Response>Successfully Sent.</Response>
<UsedCredits>1</UsedCredits>
</ResultSet>
</DocumentElement>
現在,我想解析以下響應字符串,並單獨獲取<Response>
標記的值以進行進一步處理。 既然如此,我只得到CDATA內容如何解析String內容?
顯然,您需要為此使用XML解析器。 可以說上面存儲在一個名為content
的String
變量中
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();
}
對於較大的數據集,請遵循上述解析器例程。 對多個相似數據集使用循環。 希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.