There are four types of parsing methods commonly used in Java:
Java comes with: Dom, Sax.
Plus bag: Jdom, dom4j.
1.Dom
The main way to build
Documentbuilderfactory dbf=documentbuilderfactory. newinstance ();
Documentbuilder db=dbf. Newdocumentbuilder ();
Document dm=db. Parse ("Rec\\books.xml");
Where the node class is the Nodes node collection class is NodeList
The attr Property collection is implemented with NamedNodeMap through getattributes () .
NodeList booklist=dmgetelementsbytagname("book");
NodeList childnodes = Book. Getchildnodes ();
Byte point childnodes Collection is implemented with Getchildnodes ()
Byte point I obtained by Childnodes.item (i)
The "set" length is implemented with Get.length ()
There are several types of node types that can be obtained by node.element_node
If you want to get the text in <name> data structure </name>
You need to get the text directly via Childnodes.item (k). Gettextcontent ()
or by Childnodes.item (k). Getfirstchild (). Getnodename. (text is considered a child node of the name label
Ps:xml spaces are treated as a node of the text type.
Example:
Public classXmltest { PublicList<book>Books; PublicXmltest () { This. books=NewArrayList (); } Public Static voidMain (string[] args)throwsException {Xmltest test=NewXmltest (); inti=2005; intJ=i>>2; System.out.println (j); Test. Jiexi (); Test.foreprint ();} Public voidJiexi ()throwsexception{documentbuilderfactory dbf=documentbuilderfactory.newinstance (); Documentbuilder DB=Dbf.newdocumentbuilder (); Document DM=db.parse ("E:\\books.xml");//TODO auto-generated Method StubNodeList booklist=dm.getelementsbytagname ("book"); for(inti = 0; I < booklist.getlength (); i++) {Book Temp=NewBook (); Node Book=Booklist.item (i); NamedNodeMap Attrs=book.getattributes (); NodeList childnodes=book.getchildnodes (); for(intk = 0; K < Childnodes.getlength (); k++) { if(Childnodes.item (k). Getnodetype () = =Node.element_node) { if(Childnodes.item (k). Getnodename () = = "Name") Temp.name=Childnodes.item (k). Getn; if(Childnodes.item (k). Getnodename () = = "Years") Temp.years=Childnodes.item (k). Gettextcontent (); if(Childnodes.item (k). Getnodename () = = "Price") Temp.price=Childnodes.item (k). Gettextcontent (); }} books.add (temp); } } Public voidForeprint () { for(book temp:books) {System.out.println ("------------"); System.out.println ("The title is:" +temp.name); System.out.println ("Year of publication:" +temp.years); System.out.println ("Price is:" +temp.price+ "Yuan"); } } }
View Code
Four common parsing methods in Xml--java--dom