Java中如何读取xml文件
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java里有个properties类可以用它来读取XML文件xml文件:
Xml代码
第一种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();
}
}
}
第三种JDOM实现方法:
Java代码
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.*;
public class MyXMLReader2JDOM { public static void main(String arge[]) { long lasting = System.currentTimeMillis();
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("data_10k.xml"));
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for (int i = 0; i < allChildren.size(); i++) {
System.out.print("车牌号码:"+ ((Element) allChildren.get(i)).getChild("NO").getText()); System.out.println("车主地址:"+ ((Element) allChildren.get(i)).getChild("ADDR").getText()); }
System.out.println("运行时间:" + (System.currentTimeMillis() - lasting)
+ "毫秒");
}
} catch (Exception e) {