Use Dom4j to parse XML files and dom4j to parse xml files

Source: Internet
Author: User

Use Dom4j to parse XML files and dom4j to parse xml files

Dom4j is a java xml api, similar to jdom, used to read and write XML files. It features excellent performance, powerful functionality, and easy to use.

Jar package: dom4j-1.6.1.jar

Xml file to be parsed: people. xml

1 <people city = "BeiJing"> 2 <student name = "Jack" age = "10"> My name is Jack! </Student> 3 <student name = "Lucy" age = "11"> My name is Lucy! </Student> 4 <student name = "James" age = "12"/> 5 <teacher name = "Jason" age = "25"> I am a teacher! </Teacher> 6 <teacher name = "Michael" age = "30"> I am a teacher too! </Teacher> 7 </people>People. xml

First, build a javabean Based on the xml document:

1 package bean; 2 3 import java. util. list; 4 5 public class People {6 private String city; 7 private List <Student> student; 8 private List <Teacher> teacher; 9 10 public String getCity () {11 return city; 12} 13 public void setCity (String city) {14 this. city = city; 15} 16 public List <Student> getStudent () {17 return student; 18} 19 public void setStudent (List <Student> student) {20 this. student = student; 21} 22 public List <Teacher> getTeacher () {23 return teacher; 24} 25 public void setTeacher (List <Teacher> teacher) {26 this. teacher = teacher; 27} 28}People. java 1 package bean; 2 3 public class Student {4 private String name; 5 private int age; 6 private String text; 7 public String getName () {8 return name; 9} 10 public void setName (String name) {11 this. name = name; 12} 13 public int getAge () {14 return age; 15} 16 public void setAge (int age) {17 this. age = age; 18} 19 public String getResult () {20 return text; 21} 22 public void setResult (String result) {23 this. text = result; 24} 25 public Student (String name, int age, String text) {26 super (); 27 this. name = name; 28 this. age = age; 29 this. text = text; 30} 31}Student. java 1 package bean; 2 3 public class Teacher {4 private String name; 5 private int age; 6 private String text; 7 public String getName () {8 return name; 9} 10 public void setName (String name) {11 this. name = name; 12} 13 public int getAge () {14 return age; 15} 16 public void setAge (int age) {17 this. age = age; 18} 19 public String getResult () {20 return text; 21} 22 public void setResult (String result) {23 this. text = result; 24} 25 public Teacher (String name, int age, String text) {26 super (); 27 this. name = name; 28 this. age = age; 29 this. text = text; 30} 31}Teacher. java
The parsing code is as follows:
1 package xml; 2 3 import java. io. file; 4 import java.net. URISyntaxException; 5 import java. util. arrayList; 6 import java. util. iterator; 7 import java. util. list; 8 9 import org. dom4j. document; 10 import org. dom4j. extends entexception; 11 import org. dom4j. element; 12 import org. dom4j. io. SAXReader; 13 14 import bean. people; 15 import bean. student; 16 import bean. teacher; 17 18 public class Dom4jParserXML {19 p Ublic static People parseXml (String xmlPath) {20 File xmlFile = new File (xmlPath); 21 System. out. println (xmlFile. getPath (); 22 23 if (xmlFile. exists () {24 SAXReader reader = new SAXReader (); 25 People people = new People (); 26 try {27 // read the Document stream 28 document Document document = reader. read (xmlFile); 29 // get the root node 30 Element root = document. getRootElement (); 31 32 List <Student> students = new ArrayList <Student> (); 33 L Ist <Teacher> teachers = new ArrayList <Teacher> (); 34 35 people. setCity (root. attributeValue ("city"); 36 // parse student node 37 for (Iterator <Element> iterator = root38. elementIterator ("student"); iterator. hasNext ();) {39 Element eStudent = iterator. next (); 40 String text = eStudent. getText (); 41 42 Student student = new Student (43 eStudent. attributeValue ("name"), 44 Integer. parseInt (eStudent. attributeValue ("Age"), text); 45 students. add (student); 46} 47 // parse teacher node 48 for (Iterator <Element> iterator = root49. elementIterator ("teacher"); iterator. hasNext ();) {50 Element eTeacher = iterator. next (); 51 String text = eTeacher. getText (); 52 53 Teacher teacher = new Teacher (54 eTeacher. attributeValue ("name"), 55 Integer. parseInt (eTeacher. attributeValue ("age"), text); 56 teachers. add (teacher); 57} 58 people. set Student (students); 59 people. setTeacher (teachers); 60 61 System. out. println ("Parse success! "); 62} catch (incluentexception e) {63 e. printStackTrace (); 64} 65 return people; 66} else {67 System. err. println ("File is not exist! "); 68 return null; 69} 70} 71 72 public static void main (String [] args) throws URISyntaxException {73 String xmlPath =" E: // xml // people. xml "; 74 System. out. println ("File full path is" + xmlPath); 75 // parse people. xml76 People p = parseXml (xmlPath); 77 78 // process the parsing result 79 System. out. println ("The city is:" + p. getCity (); 80 List <Student> sList = p. getStudent (); 81 List <Teacher> tList = p. getTeacher (); 82 for (Student s: sList) {83 System. out. println (s. getName () + "->" + s. getAge () + "->" + s. getResult (); 84} 85 for (Teacher t: tList) {86 System. out. println (t. getName () + "->" + t. getAge () + "->" + t. getResult (); 87} 88} 89}

Running result:

File full path is E: // xml // people. xmlE: \ xml \ people. xmlParse success! The city is: BeiJingJack-> 10-> My name is Jack! Lucy-> 11-> My name is Lucy! James-> 12-> Jason-> 25-> I am a teacher! Michael-> 30-> I am a teacher too!Result
Urgent, dom4j parses xml files

/**
*
*/
Package test. actions;

Import java. io. File;
Import java. util. List;

Import org. dom4j. Document;
Import org. dom4j. extends entexception;
Import org. dom4j. Element;
Import org. dom4j. Node;
Import org. dom4j. io. SAXReader;

/**
* @ Author Administrator
*
*/
Public class ParseXmlExample {

/**
* @ Param args
* The XML document you provide on Baidu has the format and extra spaces. Correct the document and resolve it again.
*/
Public static void main (String [] args ){
File file = new File ("your File path ");
ParseModelXml (file );
}

Private static void parseModelXml (File file ){
SAXReader reader = new SAXReader ();
Try {
// Get the XML Document Object
Document doc = reader. read (file );
// Obtain the root node
Element root = doc. getRootElement ();
String rootName = root. getName ();
List <Element> list = doc. selectNodes (rootName + "/*");
For (int I = 0; I <list. size (); I ++ ){
Element element = (Element) list. get (I );
WalkNodes (element );
}
} Catch (incluentexception e ){
E. printStackTrace ();
}
}
// Recursive Parsing
Private static void walkNodes (Element element ){

For (int I = 0; I <element. nodeCount (); I ++ ){
Node node = element. node (I );
System. out. println (node. getNodeTypeName ());
If (node instanceof Element ){
WalkNodes (Element) node );
} Else {
String str = node. getText (). trim ();
If (null = str ){
Str = "";
}
If (! "". Equals (str )){
System. out. println ("text is:" + str );
}
}
}
}
}... Remaining full text>

How to Use dom4j to parse multi-node xml files? Examples

According to your xml format. Save the preceding xml as bb. xml
SAXReader sax = new SAXReader ();
Document document = sax. read ("bb. xml ");
Element root = document. getRootElement ();

For (Iterator iter = root. elementIterator (); iter. hasNext ();){
Element vals = (Element) iter. next ();
System. out. println ("name =" + vals. getName ()
+ "\ T attribut ID =" + vals. attributeValue ("id "));
For (Iterator iterVal = vals. elementIterator (); iterVal
. HasNext ();){
Element valNode = (Element) iterVal. next ();
System. out. print ("\ t childName =" + valNode. getName ()
+ "\ T childValue =" + valNode. getText ());
System. out. println ();
}
}

If you change the xml format, save the file B. xml:
<RESULT>
<VALUE id = "13" type = "1">
<NO> 2 </NO>
<ADDR> test </ADDR>
</VALUE>
<VALUE id = "13" type = "2">
<NO> 2 </NO>
<ADDR> test </ADDR>
</VALUE>
</RESULT>

Resolution:
Document = sax. read ("B. xml ");
Root = document. getRootElement ();
List ls = root. selectNodes ("/RESULT/VALUE ");

For (int I = 0; I <ls. size (); I ++ ){
Element val = (Element) ls. get (I );
Element no = val. element ("NO ");
Element addr = val. element ("ADDR ");
System. out. println ("id =" + val. attributeValue ("id") + "\ t type ="
+ Val. attributeValue (... the remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.