我正在尝试调用web服务并打印一些响应。
当我运行此代码时,我会获得带有ID,FIRSTNAME,LASTNAME,STREET,CITY的XML响应。例如,我如何只打印出CITY?
static int customerId = 123456;
public static void main(String[] args) throws Exception {
URL oracle = new URL(
"http://www.thomas-bayer.com/sqlrest/CUSTOMER/" + customerId);
BufferedReader in = new BufferedReader(new InputStreamReader(
oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
提前谢谢。
答案 0 :(得分:0)
这可能是一个调整代码,但仍然会这样做。
static int customerId = 123456;
static String str="";
public static void main(String[] args) throws Exception
{
URL oracle = new URL("http://www.thomas-bayer.com/sqlrest/CUSTOMER/" + customerId);
BufferedReader in = new BufferedReader(new InputStreamReader(
oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
//code change stats here
if(inputLine.contains("<CITY>")){
str=inputLine;
}
}
String city=str.replace("<CITY>","");
System.out.println(city.replace("</CITY>", ""));
//code change ends here
in.close();
}
答案 1 :(得分:0)
通过传递密钥和字符串在while循环中调用此方法:
public static String getvalue(String xmlkey,String xmlstring) throws
ParserConfigurationException, SAXException, IOException{
System.out.println(xmlstring+"dff");
InputStream is = new ByteArrayInputStream(xmlstring.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = null;
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName(xmlkey);
if (nl != null) {
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
String name = item.getNodeName();
String value = item.getTextContent();
System.out.println(name+" "+value+" value and name");
}
}
return value;
} catch(Exception e) {
e.printStackTrace();
}
}