Java生成XML格式

工具:

dom4j-1.6.1.jar

相关类

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

实例1

还是直接看例子吧,最终生成结果展示:




  张三
  123456

代码如下:

    Document document = DocumentHelper.createDocument();
    //创建根节点
    Element root = document.addElement("root");
    //添加子节点
    Element username = root.addElement("username");
    Element password = root.addElement("password");
    //赋值
    username.addText("张三");
    password.addText("123456");
    String strXML = document.asXML();
    System.out.println(strXML);

实例2

适用于部分子节点封装成类,最终生成结果展示:
其中,结构是重复的,可以写成一个类Course.java;




  张三
  123456
  
    
      课程id
      语文课
      007
      王老师
    
    
      课程id2
      数学课
      008
      李老师
    
  


代码如下:


Course.java

public class Course{
    String courseId;//课程id
    String courseName;//名称
    String courseNum;//课程号
    String courseTeacher;//老师
    
    public String getCourseId() {
        return courseId;
    }
    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }
    public String getCourseName() {
        return courseName;
    }
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
    public String getCourseNum() {
        return courseNum;
    }
    public void setCourseNum(String courseNum) {
        this.courseNum = courseNum;
    }
    public String getCourseTeacher() {
        return courseTeacher;
    }
    public void setCourseTeacher(String courseTeacher) {
        this.courseTeacher = courseTeacher;
    }
}

生成xml代码:

	public static void main(String[] args) {
	    Document document = DocumentHelper.createDocument();
	    //创建根节点
        Element root = document.addElement("root");
        //添加子节点
        Element username = root.addElement("username");
        Element password = root.addElement("password");
        //赋值
        username.addText("张三");
        password.addText("123456");
        Element courses = root.addElement("courses");
        
        Course course = new Course();
        course.setCourseId("课程id");
        course.setCourseName("语文课");
        course.setCourseNum("007");
        course.setCourseTeacher("王老师");
        xmlUtil.beanToXml(course, courses, "course");
        
        Course course2 = new Course();
        course2.setCourseId("课程id2");
        course2.setCourseName("数学课");
        course2.setCourseNum("008");
        course2.setCourseTeacher("李老师");
        
        beanToXml(course2, courses, "course");
        String strXML = document.asXML();
        System.out.println(strXML);
	}

其中beanToXml方法如下,自己封装的;

	/**
	 * 将类生成xml
	 * @param object 对象
	 * @param objName 对象节点名称
	 * @return
	 */
	public  Element beanToXml(Object object,Element rootElement,String objName){
		Class clazz = object.getClass();
		Method[] methods = clazz.getDeclaredMethods();
		//Document document = DocumentHelper.createDocument(); 
		//设置xml的编码
		//document.setXMLEncoding(xmlEncoding);
		//设置根节点名称
		//Element root = document.addElement(rootName);
		//设置对象节点名称
		Element body = rootElement.addElement(objName);
		for (int i = 0; i < methods.length; i++) {
			if(methods[i].getName().substring(0,3).equals("get")){
				Element element = body.addElement(methods[i].getName().substring(3,methods[i].getName().length()).toLowerCase());
				try {
					if(methods[i].invoke(object) != null){
						element.addText(methods[i].invoke(object).toString().trim());
					}else{
						element.addText("");
					}
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					CLS_InterfaceLogger.error(e.getMessage(), e);
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					CLS_InterfaceLogger.error(e.getMessage(), e);
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					CLS_InterfaceLogger.error(e.getMessage(), e);
				}
			}
		}
		//return document.asXML();
		return body;
	}

总结:

脑子里要生成的结构,一步一步的添加或循环创建子节点,多写几次就ok了!
有问题可以加下qq交流群:700637673

你可能感兴趣的:(Java,XML,JAVA)