日期:2014-05-20 浏览次数:20932 次
<?xml version="1.0" encoding="UTF-8"?> <elements> <student sid="001"> <sheet_Amount>3456</sheet_Amount> <sheet_Approve>approved</sheet_Approve> <sheet_Name>ruantongdongli</sheet_Name> <sheet_ID>1111111111111111</sheet_ID> <sheet_Date>20090524</sheet_Date> </student> </elements>
package com.ibm.filenet.edu; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.SAXException; public class ParseXML { /*public static void main(String[] args) { List<Object> list = new ArrayList<Object>(); ParseXML instance = new ParseXML(); String filePath = "C:\\Source\\xml\\workflowElement.xml"; list = instance.parse(filePath, list); Iterator iterator = list.iterator(); System.out.println("**************************"); while(iterator.hasNext()){ System.out.println(iterator.next().toString()); } }*/ public List<Object> parse(String filePath, List<Object> list){ //List<Object> list = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); //File file = new File("C:\\Source\\xml file\\xml\\XML ppt\\xml day4\\dom_ sax\\sax\\candidate.xml"); Document dom = db.parse(filePath); System.out.println("file path: " + dom.getDocumentURI()); Element root = dom.getDocumentElement(); //root node list = Iterator(root, list); //System.out.println("********************"); //Iterator iterator = list.iterator(); //while(iterator.hasNext()){ // System.out.println(iterator.next().toString()); //} //return list; } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; } public List<Object> Iterator(Element root, List<Object> list) { NodeList nodelist = root.getChildNodes(); //List<Object> list = new ArrayList<Object>(); for (int i = 0; i < nodelist.getLength(); i++) { Node node = nodelist.item(i); if (node instanceof Text) { String value = node.getNodeValue(); if (value != null && !value.trim().equals("")) { //System.out.println("content: " + value); list.add(value); } } if (node instanceof Element) { //System.out.println("node: " + node.getNodeName()); list.add( node.getNodeName()); Iterator( (Element)node, list); } } return list; } }