Java 处理xml有很多框架,今天使用主流框架dom4j-1.6.1
下载地址:http://www.dom4j.org/dom4j-1.6.1/
Dom4j,是一款开源的处理XML, XPath, and XSLT的框架,它容易使用,并且完全支持DOM, SAX, and JAXP.
// lets write to a file XMLWriter writer = new XMLWriter( new FileWriter( "output.xml" ) );
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 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; } }View Code
接下来初始化并放到一个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); }View Code
创建一个写到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; }
SAXReader reader = new SAXReader()
Document document = reader.read(file);
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()); } }
可以通过:
运行结果:
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