java 处理XML(dom4j-1.6.1)
Java 处理xml有很多框架,今天使用主流框架dom4j-1.6.1
下载地址:http://www.dom4j.org/dom4j-1.6.1/
Dom4j,是一款开源的处理XML, XPath, and XSLT的框架,它容易使用,并且完全支持DOM, SAX, and JAXP.
写XML 文件
- 首先创建一个XMLwriter,吧文件写到output.xml
// lets write to a file XMLWriter writer = new XMLWriter( new FileWriter( "output.xml" ) );
- 创建一个xml Document
Document document = DocumentHelper.createDocument();
- 接着创建 元素的根节点
Element root = document.addElement( "root" );
- 接下来在根节点添加元素和属性
root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" );
- 最后保存文件
writer.write( document ); writer.close();
- 这样保存效果很差,很不美观,如果想要漂亮的效果
OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter("output.xml"), format);
最终的:
import java.io.FileWriter; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class XMLWriterTest { /** * @author Young * @param args * @throws IOException */ public static void main(String[] args) throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter("output.xml"), format); Document document = DocumentHelper.createDocument(); Element root = document.addElement("root"); root.addComment("This is xml comment"); root.addElement("author").addAttribute("name", "James") .addAttribute("location", "UK").addText("James Strachan"); writer.write(document); writer.close(); } }
输出效果如下:
<?xml version="1.0" encoding="UTF-8"?> <root> <!--This is xml comment--> <author name="James" location="UK">James Strachan</author> </root>
嵌套写XML
想要的效果如下:
<?xml version="1.0" encoding="UTF-8"?> <StudentInfo Class="1"> <!--This is Class 1 student information--> <student name="Jack" Sex="Male" Birthday="1988/07/05">100001 <scores score="90"/> </student> <student name="Lisa" Sex="Female" Birthday="1989/02/12">100002 <scores score="98"/> </student> <student name="Steven" Sex="Male" Birthday="1987/11/18">100003 <scores score="59"/> </student> <student name="Jenny" Sex="Female" Birthday="1989/03/18">100004 <scores score="69"/> </student> <student name="Lucy" Sex="Female" Birthday="1990/01/26">100005 <scores score="90"/> </student> <student name="Lewis" Sex="Male" Birthday="1989/04/06">100006 <scores score="82"/> </student> </StudentInfo>
每个student节点下设置一个score节点
并且所有student节点属性都一样,于是乎可以创建一个student bean专门用于数据传递:
/*** * This Class is for Student bean * @author Young * */ public class Student { private int stud_Id; private String stud_Name; private String sex; private String birthday; private String score; public int getStud_Id() { return stud_Id; } public void setStud_Id(int stud_Id) { this.stud_Id = stud_Id; } public String getStud_Name() { return stud_Name; } public void setStud_Name(String stud_Name) { this.stud_Name = stud_Name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } /** * This method is a constructor * * @author Young * @param id * @param name * @param sex * @param birthday * @param score */ public Student(int id, String name, String sex, String birthday, String score) { this.stud_Id = id; this.stud_Name = name; this.sex = sex; this.birthday = birthday; this.score = score; } }
接下来初始化并放到一个ArrayList:
static List<Student> students = new ArrayList<Student>(); /** * @author Young */ public static void init() { Student stu1 = new Student(100001, "Jack", "Male", "1988/07/05", "90"); Student stu2 = new Student(100002, "Lisa", "Female", "1989/02/12", "98"); Student stu3 = new Student(100003, "Steven", "Male", "1987/11/18", "59"); Student stu4 = new Student(100004, "Jenny", "Female", "1989/03/18", "69"); Student stu5 = new Student(100005, "Lucy", "Female", "1990/01/26", "90"); Student stu6 = new Student(100006, "Lewis", "Male", "1989/04/06", "82"); students.add(stu1); students.add(stu2); students.add(stu3); students.add(stu4); students.add(stu5); students.add(stu6); }
创建一个写到XML文件的方法:
/** * @author Young * @param studs * @return * @throws IOException */ public static Document createDocument(List<Student> studs) throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter("output.xml"), format); Document document = DocumentHelper.createDocument(); Element root = document.addElement("StudentInfo"); root.addAttribute("Class", "1"); root.addComment("This is Class 1 student information"); for (Student std : studs) { root.addElement("student").addAttribute("name", std.getStud_Name()) .addAttribute("Sex", std.getSex()) .addAttribute("Birthday", std.getBirthday()) .addText(Integer.toString(std.getStud_Id())) .addElement("scores").addAttribute("score", std.getScore()); } writer.write(document); writer.close(); return document; }
读取XML文件
- 与写文件相似,首先创建一个SAXReader
SAXReader reader = new SAXReader()
- 接着创建XML document
Document document = reader.read(file);
- 创建根元素并从document获取
Element root = document.getRootElement();
- 创建元素迭代器或属性迭代器获取相关元素和属性
// iterate through child elements of root for ( Iterator i = root.elementIterator(); i.hasNext(); ) { Element element = (Element) i.next(); // do something } // iterate through attributes of root for ( Iterator i = root.attributeIterator(); i.hasNext(); ) { Attribute attribute = (Attribute) i.next(); // do something }
以之前嵌套后的XML为例:
/**This method is for read XML * @author Young * @param file * @throws DocumentException */ public static void readDocument(String file) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(file); Element root = document.getRootElement(); for (Iterator<?> i = root.elementIterator(); i.hasNext();) { Element element = (Element) i.next(); if (!element.getName().equalsIgnoreCase("Student")) { System.out.println("StudentInfo is:"); continue; } // iterate through child elements of root with element name // "student" for (Iterator<?> j = element.attributeIterator(); j.hasNext();) { Attribute attribute = (Attribute) j.next(); System.out.print("attribute name " + attribute.getName() + " ->" + attribute.getName()); System.out.println(" attribute value " + attribute.getValue()); } System.out.println("attribute value " + element.getText()); // get path System.out.println("attribute name " + element.getName() + " ->" + element.getPath()); } }
可以通过:
getName/getPath/getValue 等方法是获取相关内容
运行结果:
attribute name name ->name attribute value Jack attribute name Sex ->Sex attribute value Male attribute name Birthday ->Birthday attribute value 1988/07/05 attribute value 100001 attribute name student ->/StudentInfo/student attribute name name ->name attribute value Lisa attribute name Sex ->Sex attribute value Female attribute name Birthday ->Birthday attribute value 1989/02/12 attribute value 100002 attribute name student ->/StudentInfo/student attribute name name ->name attribute value Steven attribute name Sex ->Sex attribute value Male attribute name Birthday ->Birthday attribute value 1987/11/18 attribute value 100003 attribute name student ->/StudentInfo/student attribute name name ->name attribute value Jenny attribute name Sex ->Sex attribute value Female attribute name Birthday ->Birthday attribute value 1989/03/18 attribute value 100004 attribute name student ->/StudentInfo/student attribute name name ->name attribute value Lucy attribute name Sex ->Sex attribute value Female attribute name Birthday ->Birthday attribute value 1990/01/26 attribute value 100005 attribute name student ->/StudentInfo/student attribute name name ->name attribute value Lewis attribute name Sex ->Sex attribute value Male attribute name Birthday ->Birthday attribute value 1989/04/06 attribute value 100006 attribute name student ->/StudentInfo/student
时间: 2024-10-06 00:45:46