糯米文學吧

位置:首頁 > IT認證 > SUN認證

Java讀取xml文件的方法

SUN認證2.84W

xml文件:

Java讀取xml文件的方法

Xml代碼

A1234

XX省XX市

B1234

XX省XX市二七區

  第一種 DOM 實現方法:

Java代碼

import ;

import mentBuilder;

import mentBuilderFactory;

import ment;

import List;

public class MyXMLReader2DOM {

public static void main(String arge[]) {

long lasting = entTimeMillis();

try {

File f = new File("data_");

DocumentBuilderFactory factory = nstance();

DocumentBuilder builder = ocumentBuilder();

Document doc = e(f);

NodeList nl = lementsByTagName("VALUE");

for (int i = 0; i < ength(); i++) {

t("車牌號碼:"+ lementsByTagName("NO")(i)irstChild()odeValue());

tln("車主地址:"+ lementsByTagName("ADDR")(i)irstChild()odeValue());

tln("運行時間:" + (entTimeMillis() - lasting)

+ "毫秒");

}

}

} catch (Exception e) {

tStackTrace();

}

}

}

  第二種,DOM4J實現方法:

Java代碼

import .*;

import .*;

import 4j.*;

import .*;

public class MyXMLReader2DOM4J {

public static void main(String arge[]) {

long lasting = entTimeMillis();

try {

File f = new File("data_");

SAXReader reader = new SAXReader();

Document doc = (f);

Element root = ootElement();

Element foo;

for (Iterator i = entIterator("VALUE"); ext();) {

foo = (Element) ();

t("車牌號碼:" + entText("NO"));

tln("車主地址:" + entText("ADDR"));

}

tln("運行時間:" + (entTimeMillis() - lasting)

+ "毫秒");

}

} catch (Exception e) {

tStackTrace();

}

}

}

  第三種 JDOM實現方法:

Java代碼

import .*;

import .*;

import .*;

import t.*;

public class MyXMLReader2JDOM {

public static void main(String arge[]) {

long lasting = entTimeMillis();

try {

SAXBuilder builder = new SAXBuilder();

Document doc = d(new File("data_"));

Element foo = ootElement();

List allChildren = hildren();

for (int i = 0; i < (); i++) {

t("車牌號碼:"+ ((Element) (i))hild("NO")ext());

tln("車主地址:"+ ((Element) (i))hild("ADDR")ext());

}

tln("運行時間:" + (entTimeMillis() - lasting)

+ "毫秒");

}

} catch (Exception e) {

tStackTrace();

}

}

}

  第四種SAX實現方法:

Java代碼

import arser;

import arserFactory;

import ibutes;

import tSource;

import xception;

import ultHandler;

public class MyXMLReader2SAX extends DefaultHandler {

k tags = new k();

public MyXMLReader2SAX() {

super();

}

public static void main(String args[]) {

long lasting = entTimeMillis();

try {

SAXParserFactory sf = nstance();

SAXParser sp = AXParser();

MyXMLReader2SAX reader = new MyXMLReader2SAX();

e(new InputSource("data_"), reader);

} catch (Exception e) {

tStackTrace();

}

tln("運行時間:" + (entTimeMillis() - lasting)

+ "毫秒");

}

public void characters(char ch[], int start, int length)

throws SAXException {

String tag = (String) ();

if (ls("NO")) {

t("車牌號碼:" + new String(ch, start, length));

}

if (ls("ADDR")) {

tln("地址:" + new String(ch, start, length));

}

}

public void startElement(String uri, String localName, String qName,

Attributes attrs) {

(qName);

}

}

標籤:JAVA XML 讀取 文件