如何解析Android中的Web服务返回的字符串?

时间:2012-07-11 13:08:35

标签: android

<string xmlns="http://tempuri.org/">
  <NewDataSet> 
     <myTable> 
         <USERNAME>admin</USERNAME> 
         <PASSWORD>123</PASSWORD> 
     </myTable> 
     <myTable> 
        <USERNAME>John</USERNAME>
        <PASSWORD>678</PASSWORD> 
     </myTable> 
    </NewDataSet>
  </string>

如何解析从android中的web服务返回的这个字符串?

1 个答案:

答案 0 :(得分:0)

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("employee");

    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);

      NodeList name = element.getElementsByTagName("name");
      Element line = (Element) name.item(0);
      System.out.println("Name: " + getCharacterDataFromElement(line));

      NodeList title = element.getElementsByTagName("title");
      line = (Element) title.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }

  }

  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterData) child;
      return cd.getData();
    }
    return "";
  }
}