2015-06-22 71 views
0

我正在通過netbeans IDE生成的Web服務客戶端調用Web服務方法。從java中的soap響應中獲取值

private String getCitiesByCountry(java.lang.String countryName) { 
     webService.GlobalWeatherSoap port = service.getGlobalWeatherSoap(); 
     return port.getCitiesByCountry(countryName); 
    } 

因此,我調用這個方法我的程序中,

String b = getWeather("Katunayake", "Sri Lanka"); 

,它會給我一個字符串輸出包含XML數據。

String b = getWeather("Katunayake", "Sri Lanka"); = (java.lang.String) <?xml version="1.0" encoding="utf-16"?> 
<CurrentWeather> 
    <Location>Katunayake, Sri Lanka (VCBI) 07-10N 079-53E 8M</Location> 
    <Time>Jun 22, 2015 - 06:10 AM EDT/2015.06.22 1010 UTC</Time> 
    <Wind> from the SW (220 degrees) at 10 MPH (9 KT):0</Wind> 
    <Visibility> greater than 7 mile(s):0</Visibility> 
    <SkyConditions> partly cloudy</SkyConditions> 
    <Temperature> 86 F (30 C)</Temperature> 
    <DewPoint> 77 F (25 C)</DewPoint> 
    <RelativeHumidity> 74%</RelativeHumidity> 
    <Pressure> 29.74 in. Hg (1007 hPa)</Pressure> 
    <Status>Success</Status> 
</CurrentWeather> 

我怎樣才能得到<Location>,<SkyConditions>,<Temperature>的價值。

回答

1

如果您只需要這3個值,您可以去XPath。否則,DOM會讀取整個文檔。那些編寫XPath expressions的人很容易直接讀取節點讀取值。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = null; 
try { 
    builder = factory.newDocumentBuilder(); 
} catch (ParserConfigurationException e) { 
    e.printStackTrace(); 
} 
String xml = ...; // <-- The XML SOAP response 
Document xmlDocument = builder.parse(new ByteArrayInputStream(xml.getBytes())); 
XPath xPath = XPathFactory.newInstance().newXPath(); 
String location = xPath.compile("/CurrentWeather/Location").evaluate(xmlDocument); 
String skyCond = xPath.compile("/CurrentWeather/SkyConditions").evaluate(xmlDocument); 
String tmp = xPath.compile("/CurrentWeather/Temperature").evaluate(xmlDocument); 

如果需要頻繁獲取許多XML節點,然後去DOM

1

使用DOM解析器,使用http://examples.javacodegeeks.com/core-java/xml/java-xml-parser-tutorial爲指導的一種方式:

String b = getWeather("Katunayake", "Sri Lanka"); 
InputStream weatherAsStream = new ByteArrayInputStream(b.getBytes(StandardCharsets.UTF_8)); 

DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = fac.newDocumentBuilder(); 
org.w3c.dom.Document weatherDoc = builder.parse(weatherAsStream); 

String location = weatherDoc.getElementsByTagName("Location").item(0).getTextContent(); 
String skyConditions = weatherDoc.getElementsByTagName("SkyConditions").item(0).getTextContent(); 
String temperature = weatherDoc.getElementsByTagName("Temperature").item(0).getTextContent(); 

這有沒有異常處理,可能會打破,如果有具有相同名稱的多個元素,但你應該能夠從這裏工作。

+0

我正在使用NetBeans IDE 7.3。當我使用getElementsByTagName(「」)它給我一個錯誤。 「找不到符號方法getElementsByTagName(String)」 – dennypanther