Person. xml
<? XML version = "1.0" encoding = "UTF-8"?>
<Persons>
<Person id = "1">
<Name> Jerry </Name>
<Age> 23 </age>
</Person>
<Person id = "3">
<Name> Lily </Name>
<Age> 17 </age>
</Person>
</Persons>
Create a JavaBean for person (because we need to obtain the content of this XML file in the form of an object below)
Package CN. partner4java. xml. Bean;
Public class person {
Private int ID;
Private string name;
Private short age;
Public int GETID (){
Return ID;
}
Public void setid (int id ){
This. ID = ID;
}
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
Public short getage (){
Return age;
}
Public void setage (short age ){
This. Age = age;
}
/**
* Use Dom to parse XML files
*
*/
Public class domxmlreader {
Public static list <person> readxml (inputstream instream ){
List <person> Persons = new arraylist <person> ();
Documentbuilderfactory factory = documentbuilderfactory. newinstance ();
Try {
Documentbuilder builder = factory. newdocumentbuilder ();
Document dom = builder. parse (instream );
Element root = Dom. getdocumentelement ();
Nodelist items = root. getelementsbytagname ("person"); // query all person nodes
For (INT I = 0; I <items. getlength (); I ++ ){
Person = new person ();
// Obtain the first person Node
Element personnode = (element) items. item (I );
// Obtain the ID attribute value of the person Node
Person. setid (New INTEGER (personnode. getattribute ("ID ")));
// Obtain all subnodes under the person node (blank nodes and Name/age elements between labels)
Nodelist childsnodes = personnode. getchildnodes ();
For (Int J = 0; j <childsnodes. getlength (); j ++ ){
Node node = (node) childsnodes. Item (j); // determines whether the element type is used.
If (node. getnodetype () = node. element_node) {element childnode = (element) node;
// Determine whether the name element is used
If ("name". Equals (childnode. getnodename ())){
// Obtain the text node under the name element, and then obtain the data person. setname (childnode. getfirstchild (). getnodevalue () from the text node ());
} Else if ("Age". Equals (childnode. getnodename ())){
Person. setage (new short (childnode. getfirstchild (). getnodevalue ()));
}
}
}
Persons. Add (person );
}
Instream. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
Return persons;
}