package test;import java.io.*; import java.util.*; import org.w3c.dom.*; import javax.xml.parsers.*; public class XML{ public static void main(String [] args){ File file=new File("XML.xml"); long startTime=System.currentTimeMillis(); System.out.println("DOM解释开始:========="); domParse(file); System.out.println("所花时间为"+(System.currentTimeMillis()-startTime)); } public static void domParse(File file){ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();//创建DOM解析工厂 try{ DocumentBuilder builder=factory.newDocumentBuilder(); Document doc=builder.parse(file); //工厂解析文件返回一个Document对像 NodeList nl=doc.getElementsByTagName("VALUE"); //找到value结点 for (int i = 0; i<nl.getLength(); i++){ StringBuffer num=new StringBuffer(); num.append("车片号:"); num.append(doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue()); num.append("\n地址"); num.append(doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue()); System.out.println(num.toString()); } }catch(Exception ex){ ex.printStackTrace(); } } }//以下为XML内容 <?xml version="1.0" encoding="GB2312"?><!-- edited with XMLSPY v2004 rel. 2 U (http://www.xmlspy.com) by newer (newer) --><RESULT> <VALUE> <NO>A1234</NO> <ADDR>四川省XX县XX镇XX路X段XX号</ADDR> </VALUE> <VALUE> <NO>B1234</NO> <ADDR>四川省XX市XX乡XX村XX组</ADDR> </VALUE></RESULT>

评论