Java 从xml格式的响应中读取数据

Java 从xml格式的响应中读取数据,java,android,xml,response,xml-parsing,Java,Android,Xml,Response,Xml Parsing,我正在开发一个应用程序,因为我已经读取了以xml格式从respose获取的数据。那么如何实施呢 我不是在我这边开发web应用程序。但是检索一个url,我将得到一个xml数据作为响应 您可以使用内置的DOM解析器 链接: 教程:以轻松的解析方式查看 创建一个类XMLfunctions public class XMLfunctions { public final static Document XMLfromString(String xml){ Document doc = nul

我正在开发一个应用程序,因为我已经读取了以xml格式从respose获取的数据。那么如何实施呢


我不是在我这边开发web应用程序。但是检索一个url,我将得到一个xml数据作为响应

您可以使用内置的DOM解析器

链接:


教程:

以轻松的解析方式查看


创建一个类XMLfunctions

public class XMLfunctions {

public final static Document XMLfromString(String xml){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }

    return doc;

}


/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
 public final static String getElementValue( Node elem ) {
     Node kid;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                 if( kid.getNodeType() == Node.TEXT_NODE  ){
                     return kid.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

    public static String getTopNewsXML(){    
        String line = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("url");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        }
        String st= ParseXMLNode(line,"doc");
        return st;

    }

public static String ParseXMLNode(String str,String node){
     String xmlRecords = str;
     String results = "";
     String[] result = new String [10];
     StringBuffer sb = new StringBuffer();
     try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         InputSource is = new InputSource();
         is.setCharacterStream(new StringReader(xmlRecords));
         Document doc = db.parse(is);
         NodeList nlist = doc.getElementsByTagName(node);

         sb.append("<results count=");
         sb.append("\"10\"");
         sb.append(">\r\n");


         for (int i = 0; i < nlist.getLength(); i++) {
                Node node1 = nlist.item(i);
                if (node1.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node1;
                    NodeList nodelist = element.getElementsByTagName("str");
                    Element element1 = (Element) nodelist.item(0);
                    NodeList title = element1.getChildNodes();

                    System.out.print((title.item(0)).getNodeValue());
                    sb.append("<result>\r\n");
                        sb.append("<title>");
                            sb.append(title.item(0).getNodeValue().trim());
                        sb.append("</title>\r\n");

                    sb.append("</result>\r\n");
                    result[i] = title.item(0).getNodeValue();

                   }
            }
         sb.append("</results>");
     } catch (Exception e) {
         System.out.println("Exception........"+results );
         e.printStackTrace();
     }
     return sb.toString();
     }
}

public static int numResults(Document doc) {
    Node results = doc.getDocumentElement();
    int res = -1;
    try {
        res = Integer.valueOf(results.getAttributes().getNamedItem("count")
                .getNodeValue());
    } catch (Exception e) {
        res = -1;
    }
    return res;
}

public static String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return XMLfunctions.getElementValue(n.item(0));
}
公共类函数{
公共最终静态文档XMLfromString(字符串xml){
单据单据=空;
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
试一试{
DocumentBuilder db=dbf.newDocumentBuilder();
InputSource is=新的InputSource();
is.setCharacterStream(新的StringReader(xml));
doc=db.parse(is);
}捕获(ParserConfiguration异常e){
System.out.println(“XML解析错误:+e.getMessage());
返回null;
}捕获(SAXE异常){
System.out.println(“错误的XML文件结构:+e.getMessage());
返回null;
}捕获(IOE异常){
System.out.println(“I/O验证:+e.getMessage());
返回null;
}
退货单;
}
/**返回元素值
*@param elem元素(它是XML标记)
*@返回元素值,否则为空字符串
*/
公共最终静态字符串getElementValue(节点元素){
节点儿童;
if(elem!=null){
if(elem.hasChildNodes()){
for(kid=elem.getFirstChild();kid!=null;kid=kid.getNextSibling()){
if(kid.getNodeType()==Node.TEXT\u节点){
return kid.getNodeValue();
}
}
}
}
返回“”;
}
公共静态字符串getTopNewsXML(){
字符串行=null;
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“url”);
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
line=EntityUtils.toString(httpEntity);
}捕获(不支持的编码异常e){
line=“无法连接到服务器”;
}捕获(格式错误){
line=“无法连接到服务器”;
}捕获(IOE异常){
line=“无法连接到服务器”;
}
字符串st=ParseXMLNode(第行,“doc”);
返回st;
}
公共静态字符串ParseXMLNode(字符串str,字符串节点){
字符串xmlRecords=str;
字符串结果=”;
字符串[]结果=新字符串[10];
StringBuffer sb=新的StringBuffer();
试一试{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
InputSource is=新的InputSource();
is.setCharacterStream(新的StringReader(xmlRecords));
文档doc=db.parse(is);
NodeList nlist=doc.getElementsByTagName(节点);
sb.追加(“\r\n”);
对于(int i=0;i
在你的活动中

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        String xml = XMLfunctions.getTopNewsXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);
        Log.d(LOG_TAG, "Number of Results: " + numResults);
        if ((numResults <= 0)) {
            Toast.makeText(ParentActivity.this, "No Result Found",Toast.LENGTH_LONG).show();
            return null;
        }

        NodeList nodes = doc.getElementsByTagName("result");

        for (int i = 0; i < nodes.getLength(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();

            Element e = (Element) nodes.item(i);
            map.put("title", XMLfunctions.getValue(e, "title"));
            mylist.add(map);
        }
        return mylist;
ArrayList mylist=new ArrayList();
字符串xml=XMLfunctions.getTopNewsXML();
Document doc=XMLfunctions.XMLfromString(xml);
int numResults=XMLfunctions.numResults(doc);
Log.d(Log_标签,“结果数:”+numResults);
如果((numResults)