Java Parsing XML document
First, parse the XML document way:
1, Dom mode: The entire XML document is read into memory, according to the XML file tree structure diagram to parse.
2, Sax mode: Based on event parsing, only need to load part of the data in the XML, the advantage is that the use of less resources, memory consumption is small.
XML document:
<?XML version= "1.0" encoding= "UTF-8"?><Students><Student><Name> Zhang San</Name><Age>20</Age></Student><Student><Name> John Doe</Name><Age>22</Age></Student><Student><Name> Harry</Name><Age>24</Age></student> <student> <name > Zhao Liu </name> <age>21< Span style= "color: #0000ff;" ></age> </< Span style= "color: #800000;" >student></ Students>
Second, Dom parsing mode:
Documentbuilderfactory DBF =Documentbuilderfactory.newinstance ();D Ocumentbuilder db =Dbf.newdocumentbuilder ();D ocument doc = db.parse ("Src/students.xml"); NodeList list = doc.getelementsbytagname ("Student"); For (int i = 0; i < list.getlength (); i++) {node node = List.item (i); NodeList stulist = node.getchildnodes (); For (int j = 0; J < Stulist.getlength (); j + +) {
An empty element #text is included by default in the XML and needs to be skipped if (Stulist.item (j). Getnodename (). Equals ("#text")) continue; Node Childnode = Stulist.item (j); System.out.println (Childnode.getnodename () + ":" + childnode.gettextcontent ());}}
Output Result:
Name: Zhang San age:20name: John Doe age:22name: Harry Age:24
Java Parsing XML document