Struts2 XML文档解析

根据这个XML文件来进行解析

<?xml version="1.0" encoding="UTF-8"?>
<students>
	<student age="28">
		<name>崔卫兵</name>
		<college>PC学院</college><!--如果没有leader属性,默认为leader -->
		<telephone>62354666</telephone>
		<notes>男,1985年生,硕士,现就读于北京邮电大学</notes>
	</student>
	<student><!--如果没有age属性,默认为20 -->
		<name>张洪泽</name>
		<college leader="leader">PC学院</college>
		<telephone>62358888</telephone>
		<notes>男,1987年生,硕士,现就读于中国农业大学</notes>
	</student>
</students>

 

Dom4jExmple

package dom4j.demo;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jExmple {
	public static void main(String[] args) {
		String filename = System.getProperty("user.dir") + "/newfile.xml";
		Dom4jExmple dom4j = new Dom4jExmple();
		dom4j.createNewDocument(filename); // 创建新XML文档
		// dom4j.addNewElement(filename); // 添加新元素
		// dom4j.modifyElement(filename); // 修改元素
		// dom4j.deleteElement(filename); // 删除元素
	}

	public void createNewDocument(String filename) {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("students"); // 创建根元素

		Element student = root.addElement("student").addAttribute("age", "27");
		student.addElement("name").addText("新人一枚");
		student.addElement("college").addAttribute("leader", "leader")
				.addText("游戏学院");
		student.addElement("telephone").addText("62355566");
		student.addElement("notes").addText("男,1986年生,硕士,现就读于中国农业大学");

		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer;
		try {
			writer = new XMLWriter(new FileWriter(filename), format);
			writer.write(document);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("OK");
	}

	public void addNewElement(String filename) {

		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(new File(filename));
			Element root = document.getRootElement();

			Element student = root.addElement("student").addAttribute("age",
					"30");
			student.addElement("name").addText("又来一个");
			student.addElement("college").addAttribute("leader", "leader")
					.addText("游戏学院");
			student.addElement("telephone").addText("62357788");
			student.addElement("notes").addText("男,1983年生,博士,现就读于中国矿业大学");

			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(new FileWriter(filename), format);
			writer.write(document);
			writer.close();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("O.K.");
	}

	public void modifyElement(String filename) {
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(new File(filename));
			Element root = document.getRootElement();

			for (Iterator iter = root.elementIterator(); iter.hasNext();) {
				Element element = (Element) iter.next();
				if (element.element("name").getText().equals("又来一个")) {
					element.element("telephone").setText("62350000");
					break;
				}
			}

			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(new FileWriter(filename), format);
			writer.write(document);
			writer.close();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("O.K.");
	}
	
	public void deleteElement(String filename) {
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(new File(filename));
			Element root = document.getRootElement();
			
			for (Iterator iter = root.elementIterator(); iter.hasNext();) {
				Element element = (Element) iter.next();
				if (element.element("name").getText().equals("又来一个")) {
					root.remove(element);
					break;
				}
			}
			
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(new FileWriter(filename), format);
			writer.write(document);
			writer.close();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("O.K.");
	}

}

 

Dom4jReadExmple

package dom4j.demo;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jReadExmple {
	/**
	 * 遍历整个XML文件,获取所有节点的值与其属性的值,并放入HashMap中
	 * 
	 * @param filename
	 *            String 待遍历的XML文件(相对路径或者绝对路径)
	 * @param hm
	 *            HashMap 存放遍历结果
	 */
	public void iterateWholeXML(String filename, HashMap<String, String> hm) {
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(new File(filename));
			Element root = document.getRootElement();
			int num = -1; // 用于记录学生编号的变量
			// 遍历根元素(students)的所有子节点(肯定是student节点)
			for (Iterator iter = root.elementIterator(); iter.hasNext();) {
				Element element = (Element) iter.next();
				num++;
				// 获取person节点的age属性的值
				Attribute ageAttr = element.attribute("age");
				if (ageAttr != null) {
					String age = ageAttr.getValue();
					if (age != null && !age.equals("")) {
						hm.put(element.getName() + "-" + ageAttr.getName()
								+ num, age);
					} else {
						hm.put(element.getName() + "-" + ageAttr.getName()
								+ num, "20");
					}
				} else {
					hm.put(element.getName() + "-age" + num, "20");
				}
				// 遍历student节点的所有子节点(即name、college、telphone和notes),
				// 并处理
				for (Iterator iterInner = element.elementIterator(); iterInner
						.hasNext();) {
					Element elementInner = (Element) iterInner.next();
					if (elementInner.getName().equals("college")) {
						hm.put(elementInner.getName() + num,
								elementInner.getText());
						// 获取college节点的leader属性的值
						Attribute leaderAttr = elementInner.attribute("leader");
						if (leaderAttr != null) {
							String leader = leaderAttr.getValue();
							if (leader != null && !leader.equals("")) {
								hm.put(elementInner.getName() + "-"
										+ leaderAttr.getName() + num, leader);
							} else {
								hm.put(elementInner.getName() + "-"
										+ leaderAttr.getName() + num, "leader");
							}
						} else {
							hm.put(elementInner.getName() + "-leader" + num,
									"leader");
						}
					} else {
						hm.put(elementInner.getName() + num,
								elementInner.getText());
					}
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}

 

TestDom4jReadExmple

package dom4j.demo;

import java.util.HashMap;

public class TestDom4jReadExmple {
	public static void main(String[] args) {
		try {
			// 获取解析完后的解析信息
			HashMap<String, String> hashMap;
			Dom4jReadExmple drb = new Dom4jReadExmple();
			// 遍历整个XML文件
			hashMap = new HashMap<String, String>();
			String n = System.getProperty("user.dir");// 获取当前工程真实路径
			// studentInfo.xml保存学生信息,放在src目录下
			drb.iterateWholeXML(n + "\\src\\studentInfo.xml", hashMap);
			for (int i = 0; i < hashMap.size(); i += 6) {
				int j = i / 6;
				System.out.print(hashMap.get("name" + j) + "\t");
				System.out.print(hashMap.get("student-age" + j) + "\t");
				System.out.print(hashMap.get("college" + j) + "\t");
				System.out.print(hashMap.get("college-leader" + j) + "\t");
				System.out.print(hashMap.get("telephone" + j) + "\t");
				System.out.println(hashMap.get("notes" + j) + "\t");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

 

TestDom4jReadExmple 效果图
Struts2 XML文档解析
 

 

你可能感兴趣的:(struts2)