XML Generation and Parsing

Ready to work

1. Employee tools
class Emp {

	private int id;
	private String name;
	private int age;
	private String gender;
	private int salary;
	
	public Emp(){	}
	public Emp(int id, String name, int age, String gender, int salary) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.gender = gender;
		this.salary = salary;
	}
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return id+", "+name+", "+age+", "+gender+", "+salary;
	}
}
2. Packages that need to be imported
dom4j supports xml generation and parsing
 jaxen supports the use of xpath in Document parsing

Generate xml document steps

1. Create a Document object to represent an xml document

2. Add elements to the Document object

3. Add child elements to the root element according to a predetermined format and finally form a predetermined format

4. Create XmlWriter

5. Write out Document through XMLWriter

//Use DOM to generate xml document
public static void writeXML() throws IOException{

	List<Emp> empList = new ArrayList<Emp>();
	empList.add(new Emp(1, "张三", 25, "男", 4000));
	empList.add(new Emp(2, "李四", 26, "女", 5000));
	empList.add(new Emp(3, "王五", 27, "男", 6000));
	empList.add(new Emp(4, "赵六", 28, "女", 7000));
	empList.add(new Emp(5, "钱七", 29, "男", 8000));

	//The first step
 	Document doc = DocumentHelper.createDocument();
 	/*
 	* The second step
 	* Doucument provides a method for adding root elements:
 	* Element addElement(String name)
 	* Add the root element with the specified name to the specified document, and Return it as an instance of Element so you can continue to do other operations to the root element
 	* Note that this method can only be called once. Because an xml document can only have one root element
 	*/
 	Element root = doc.addElement("list");
 	//The third step is
 	for(Emp emp : empList){
	 	/*
	 	* The employee information represented by each emp instance is represented by An <emp> tag is stored in the xml document
	 	* 
	 	* Element provides methods:
	 	* Element addElement(String name)
	 	* Add a subtag with the given name to the current tag, and represent and return as an Element instance
	 	*/
 		Element empEle = root .addElement("emp");
 		//Add name
 		Element nameEle = empEle.addElement("name");
 		/*
		* Element provides methods:
 		* Element addText(String text)
 		* Add the specified text information to the current label
 		*/
 		nameEle.addText(emp.getName());
 		//Add age
 		Element ageEle = empEle.addElement("age" );
 		ageEle.addText(emp.getAge()+"");
 		//Add
 		genderEle = empEle.addElement("gender");
 		genderEle.addText(emp.getGender());
 		//Add salary
 		Element salaryEle = empEle.addElement("salary");
 		salaryEle.addText(emp.getSalary()+"");
 /*
 * Element provides a method to add attributes:
 * Element addAttribute(String name, String value)
 */
 empEle.addAttribute( "id", emp.getId()+"");
	 }
 //The fourth step
		
											
			XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
	writer.setOutputStream(new FileOutputStream("myemp.xml"));
	//第五步
	writer.write(doc);
	System.out.println("写出完毕!");
	writer.close();
	
}

Use dom to parse xml document steps

1. Create SAXReader

2. Use SAXReader to read and parse the xml document. After parsing, a Document object will be returned, which represents the content of the parsed xml document (this step is where the dom is time-consuming and expensive, because all the xml documents will be read and completed. loaded into memory)

3. Get the root element through Document

4. According to the document structure, the child elements are obtained step by step starting from the root element, which has achieved the purpose of traversing the content of the xml document

//Use dom to parse the xml document
public static void parseXML() throws FileNotFoundException, DocumentException{
	
	//first step
	SAXReader reader = new SAXReader();
	// second step
	Document doc = reader.read(new FileInputStream("myemp.xml"));
	
	/*
	 * The third step gets the root element
	 * Document provides methods to get the root element:
	 * Element gotRootElement ()
	 *
	 * Element
	 * Each Element instance represents an element in the xml document, namely:
	 * A pair of tags can obtain the relevant information in the tag represented by the instance through the Element instance
	 * For example, the attribute of the name tag of the tag, and all the subtags contained in the tag
	 */
	Element root = doc.getRootElement ();
	/*
	 * String getName() get the tag name
	 */
	System.out.println("The root label name is: "+root.getName());
	
	/*
	 * the fourth step
	 * Parse the content of the xml document and get all the employee information saved in it
	 * Each employee can be saved with an instance of Emp after parsing
	 */
	//This collection is used to save all parsed employee information
	List<Emp> empList = new ArrayList<Emp>();
	
	/**
	 * Element provides related methods to get child tags. Commonly used are:
	 *
	 * Element element(String name) Get the subtag with the specified name under the current tag (commonly used when the subtag name is not repeated)
	 *
	 * List elements() Get all the subtags under the current table tag, the returned set is a number of Element instances, each instance represents one of the subtags
	 *
	 * List elements(String name) Get all subtags with the specified name under the current tag (used when the subtag names are repeated)
	 *
	 * String getText() Get the text in the current label
	 *
	 * String getTextTrim() After getting the text in the label, it will also remove the blanks at both ends of the string
	 */
	//Get all subtags in the tag
	List<Element> list = root.elements();
	// Traverse all sub tags, each one is an emp tag
	for(Element each : list){
		//get the value of name
		Element nameEle = each.element("name"); //Get the <name> tag
		String name = nameEle.getText(); //Get the text in the label
		//Get the age value
		int age = Integer.parseInt(each.elementText("age"));
		//get gender
		String gender = each.elementText("gender");
		//get salary
		int salary = Integer.parseInt(each.elementText("salary"));
		
		/*
		 * Attribute attribute(int index)
		 * Attribute attribute(String name)
		 * Get the attributes in the current tag
		 *
		 * Each instance of Attribute is used to represent an attribute of the label
		 */
		Attribute attr = each.attribute("id");
		int id = Integer.parseInt(attr.getValue());
		System.out.print(id+"\t"+name+"\t"+gender+"\t"+age+"\t"+salary);
		System.out.println();
		
		Emp emp = new Emp(id, name, age, gender, salary);
		empList.add(emp);
	}
	
	System.out.println("Parsing completed!");
	System.out.println("Get "+empList.size()+" employee information");
	for(Emp emp1 : empList){
		System.out.println(emp1);
	}
	
}

Retrieve data using xpath

// retrieve xml data using xpath
public static void useXpath(){
	
	try {
		
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new FileInputStream("myemp.xml"));
		String xpath = "/list/emp[name ='王五']/gender";
		List<Element> list = doc.selectNodes(xpath);
		for(Element e : list){
			System.out.println(e.getText());
		}
		
	} catch (Exception e) {
		e.getStackTrace();
	}
	
}









Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325562310&siteId=291194637