教你如何用Java读取xml文件
本篇文章教你如何用Java读取xml文件。
xml文件:
Xml代码
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>河南省郑州市</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>河南省郑州市二七区</ADDR>
</VALUE>
</RESULT>
第一种 DOM 实现方法: Java代码
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class MyXMLReader2DOM {
public static void main(String arge[]) {
long lasting = System.currentTimeMillis();
try {
File f = new File("data_10k.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList nl = doc.getElementsByTagName("VALUE");
for (int i = 0; i < nl.getLength(); i++) {
System.out.print("车牌号码:"+ doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());
System.out.println("车主地址:"+ doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());
System.out.println("运行时间:" + (System.currentTimeMillis() - lasting)
+ "毫秒");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二种,DOM4J实现方法: Java代码
import java.io.*;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.*;
public class MyXMLReader2DOM4J {
public static void main(String arge[]) {
long lasting = System.currentTimeMillis();
try {
File f = new File("data_10k.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(f);
Element root = doc.getRootElement();
Element foo;
for (Iterator i = root.elementIterator("VALUE"); i.hasNext();) {
foo = (Element) i.next();
System.out.print("车牌号码:" + foo.elementText("NO"));
System.out.println("车主地址:" + foo.elementText("ADDR"));
}
System.out.println("运行时间:" + (System.currentTimeMillis() - lasting)
+ "毫秒");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}