1

我正在尝试调用网络服务并打印一些响应。

当我运行此代码时,我得到带有 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();

    }

先感谢您。

4

2 回答 2

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();

}
于 2013-01-27T12:24:50.940 回答
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();
    }
                    
}
于 2013-01-27T12:36:03.137 回答