2013-09-26 114 views
0

如何解析/獲取位置節點值:印度新德里使用循環,以及如何從此xml文件獲取多個教育節點值(如SVM,HHHHH等)。 的XML:如何從XML響應中解析/獲取節點數據?

<?xml version="1.0" encoding="UTF-8"?> 
<facebookfriends> 
<data> 
<id> 
[Removed] 
    </id> 
    <location> 
     <id> 
      [Removed] 
     </id> 
     <name> 
      New Delhi, India 
     </name> 
    </location> 
    <name> 
     XYZZZZZZZZZZ 
    </name> 
    <education> 
     <school> 
      <id> 
       [Removed] 
      </id> 
      <name> 
       SVM 
      </name> 
     </school> 
     <year> 
      <id> 
       [Removed] 
      </id> 
      <name> 
       2001 
      </name> 
     </year> 
     <type> 
      High School 
     </type> 
    </education> 
    <education> 
     <concentration> 
      <id> 
       [Removed] 
      </id> 
      <name> 
       Computer Science 
      </name> 
     </concentration> 
     <school> 
      <id> 
       [Removed] 
      </id> 
      <name> 
       HHHHHHHHHHHHH 
      </name> 
     </school> 
     <type> 
      Graduate School 
     </type> 
</education> 
</data> 

</facebookfriends> 

回答

0

下面的代碼將幫助您通過解析xml來獲取位置/名稱節點值。同樣,只需更改xpath即可獲得其他節點值。

 File xmlFile = new File("C:/face.xml"); 
     DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder; 
     try{ 
      builder = builderFactory.newDocumentBuilder(); 
      Document document = builder.parse(xmlFile); 
      XPath xPath = XPathFactory.newInstance().newXPath(); 
      String exp = "/facebookfriends/data/location/name"; 
      NodeList nodeList = (NodeList) xPath.compile(exp).evaluate(document, XPathConstants.NODESET); 
      for (int i = 0; i < nodeList.getLength(); i++) { 
       System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
      } 
     }catch (ParserConfigurationException e) { 
      e.printStackTrace(); 
     } catch (XPathExpressionException e) { 
      e.printStackTrace(); 
     }