Java read XML file (1)
ReadXml.java
PackageRead;ImportJava.io.IOException;ImportJava.util.ArrayList;ImportJavax.xml.parsers.DocumentBuilder;ImportJavax.xml.parsers.DocumentBuilderFactory;ImportJavax.xml.parsers.ParserConfigurationException;ImportOrg.w3c.dom.Document;ImportOrg.w3c.dom.Node;ImportOrg.w3c.dom.NodeList;ImportOrg.xml.sax.SAXException;//------------------------------------------------//[email protected] River (Zhenjiang) 2015-4-22------------//------------------------------------------------ Public class ReadXml {Public Document loadXml(String file) {Documentbuilderfactory dbf = documentbuilderfactory.newinstance ();Try{Documentbuilder db = Dbf.newdocumentbuilder (); Document document = Db.parse (file);returnDocument }Catch(Parserconfigurationexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(Saxexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }return NULL; }Public arraylist<string> read(node node) {Arraylist<string> arrlist =NewArraylist<string> ();returnRead (node, arrlist); } Private arraylist<string> read(node node, arraylist<string> arrlist) {if(Node.getnodetype () = = node. Element_node) Arrlist.add (Node.getnodename ()); NodeList list = Node.getchildnodes (); for(inti =0; I < list.getlength (); i++) {Read (List.item (i), arrlist); }returnArrlist; }Public static void main(string[] args) {READXML ReadXml =NewREADXML (); Document doc = Readxml.loadxml ("Class.xml"); arraylist<string> list = Readxml.read (DOC); for(String str:list) {System.out.println (str); } }}
class.xml
<?xml version= "1.0" encoding= "Utf-8"?>< class > < student id="A01"> < name >Stephen chow</ name > < age >23</ Age > < introduction >Study hard</ Introduction > </ Students > < student id="A02">>< name >Brigitte</ name > < age >32</ Age > < introduction >is a good student</ Introduction > </ Students > < Student 2 id="A03">>< name >Brigitte</ name > < age >32</ Age > < introduction >is a good student</ Introduction > </ students 2></ class >
Java read XML file (1)