技术开发 频道

四种方法教你如何用Java读取xml文件

  第三种 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) {
e.printStackTrace();
}
}
}

   第四种SAX实现方法:

  Java代码

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLReader2SAX extends DefaultHandler {
java.util.Stack tags
= new java.util.Stack();
public MyXMLReader2SAX() {
super();
}
public static void main(String args[]) {
long lasting = System.currentTimeMillis();
try {
SAXParserFactory sf
= SAXParserFactory.newInstance();
SAXParser sp
= sf.newSAXParser();
MyXMLReader2SAX reader
= new MyXMLReader2SAX();
sp.parse(
new InputSource("data_10k.xml"), reader);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(
"运行时间:" + (System.currentTimeMillis() - lasting)
+ "毫秒");
}
public void characters(char ch[], int start, int length)
throws SAXException {
String tag = (String) tags.peek();
if (tag.equals("NO")) {
System.out.print(
"车牌号码:" + new String(ch, start, length));
}
if (tag.equals("ADDR")) {
System.out.println(
"地址:" + new String(ch, start, length));
}
}
public void startElement(String uri, String localName, String qName,
Attributes attrs) {
tags.push(qName);
}
}
0
相关文章