Java讀取XML文件實現方法

 1、使用JAVA javax.xml.parsers ,org.w3c.dom,org.xml.sax    下的相關類來實現,(DocumentBuilder,DocumentBuilderFactory,Document,Element,Node,NodeList)

XML文件內容如下:
 
  1. <struts> 
  2.     <package name="dotashop-default" namespace="/" extends="struts-default"> 
  3.         <action name="index"> 
  4.             <result>/index.jsp</result> 
  5.             <result>/index2.jsp</result> 
  6.             <result>/index3.jsp</result> 
  7.             <result>/index4.jsp</result> 
  8.             <result>/index5.jsp</result> 
  9.             <result>/index6.jsp</result> 
  10.             <result>/index7.jsp</result> 
  11.             <result>/index8.jsp</result> 
  12.         </action> 
  13.     </package> 
  14. </struts> 
要求讀出標籤<result></result>內的內容?
Java代碼實現如下:
 
  1. import java.io.File; 
  2. import java.io.IOException; 
  3.  
  4. import javax.xml.parsers.DocumentBuilder; 
  5. import javax.xml.parsers.DocumentBuilderFactory; 
  6. import javax.xml.parsers.ParserConfigurationException; 
  7.  
  8. import org.w3c.dom.Document; 
  9. import org.w3c.dom.Element; 
  10. import org.w3c.dom.Node; 
  11. import org.w3c.dom.NodeList; 
  12. import org.xml.sax.SAXException; 
  13.  
  14. public class S { 
  15.    public static void main(String[] args) { 
  16.     try { 
  17.    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   DocumentBuilder db = factory.newDocumentBuilder(); 
  18.     Document doc = db.parse(new File("E:/JavaWork/test/src/com/test/struts.xml")); 
  19.     Element elmtInfo = doc.getDocumentElement(); 
  20.     NodeList nodes = elmtInfo.getChildNodes(); 
  21.     int m = 1
  22.     for (int i = 0; i < nodes.getLength(); i++) { 
  23.         Node result = nodes.item(i); 
  24.         if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("package")) { 
  25.         NodeList ns = result.getChildNodes(); 
  26.     for (int j = 0; j < ns.getLength(); j++) { 
  27.         Node record = ns.item(j); 
  28.         if (record.getNodeType() == Node.ELEMENT_NODE && record.getNodeName().equals("action")) { 
  29.         NodeList ks = record.getChildNodes(); 
  30.     for (int k = 0; k < ks.getLength(); k++) { 
  31.         Node re = ks.item(k); 
  32.         if (re.getNodeType() == Node.ELEMENT_NOD && re.getNodeName().equals("result")) { 
  33.         System.out.println(m + ": "+ re.getTextContent()); 
  34.         m++; 
  35.         } 
  36.     } 
  37.  
  38.     } 
  39.     } 
  40.     } 
  41.     } 
  42.     } catch (ParserConfigurationException e) { 
  43.             e.printStackTrace(); 
  44.     } catch (SAXException e) { 
  45.             e.printStackTrace(); 
  46.     } catch (IOException e) { 
  47.             e.printStackTrace(); 
  48.     } 
  49.     } 
運行結果:
1: /index.jsp
2: /index2.jsp
3: /index3.jsp
4: /index4.jsp
5: /index5.jsp
6: /index6.jsp
7: /index7.jsp
8: /index8.jsp

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章