Java&Xml 튜토리얼 (8) JDOM을 사용하여 Java 객체를 XML로 변환

黄舟
풀어 주다: 2017-02-22 14:55:02
원래의
1660명이 탐색했습니다.

이전 튜토리얼에서는 JDOM을 사용하여 XML 파일의 내용을 구문 분석하고 수정하는 방법을 배웠습니다. 이 섹션에서는 Java 객체를 XML 데이터로 변환하고 파일을 생성하는 방법을 소개합니다.

JDOM의 Document 클래스는 요소와 속성을 생성하는 편리한 방법을 제공합니다. XMLOutputter 클래스는 모든 OutputStream 및 Writer 객체에 Document를 쓸 수 있습니다.
이 예에서는 Employee 개체 컬렉션을 만들고 이를 XML 파일에 씁니다.
Employee.java

package com.journaldev.xml;
public class Employee {    
private int id;    
private String name;    
private String gender;    
private int age;    
private String role;    
public Employee(){}    
public Employee(int id, String name, int age, String gender, String role){        
this.id=id;        
this.age=age;        
this.name=name;        
this.gender=gender;        
this.role=role;
    }    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 String getGender() {        
    return gender;
    }    public void setGender(String gender) {        
    this.gender = gender;
    }    public int getAge() {        
    return age;
    }    public void setAge(int age) {        
    this.age = age;
    }    public String getRole() {        
    return role;
    }    public void setRole(String role) {        
    this.role = role;
    }

}
로그인 후 복사
로그인 후 복사

Employee 개체 ID를 XML 파일의 Employee 요소 속성으로 사용하고 루트 요소 Employees의 네임스페이스를 "http://www.php.php"로 설정합니다. cn/"
JDOMXMLWriter.java

package com.journaldev.xml.jdom;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import com.journaldev.xml.Employee;
public class JDOMXMLWriter {

    public static void main(String[] args) throws IOException {
        List<Employee> empList = new ArrayList<>();
        empList.add(new Employee(1, "Pankaj",25,"Male","Java Developer"));
        empList.add(new Employee(2, "Mona",34,"Female","Manager"));
        empList.add(new Employee(3, "Dave",45,"Male","Support"));

        String fileName = "employees.xml";
        writeFileUsingJDOM(empList, fileName);
    }

    private static void writeFileUsingJDOM(List<Employee> empList, String fileName) throws IOException {
        Document doc = new Document();
        doc.setRootElement(new Element("Employees",  Namespace.getNamespace("http://www.journaldev.com/employees")));
        for(Employee emp : empList){
            Element employee = new Element("Employee");
            employee.setAttribute("id",""+emp.getId());
            employee.addContent(new Element("age").setText(""+emp.getAge()));
            employee.addContent(new Element("name").setText(emp.getName()));
            employee.addContent(new Element("gender").setText(emp.getGender()));
            employee.addContent(new Element("role").setText(emp.getRole()));
            doc.getRootElement().addContent(employee);
        }
        //JDOM document is ready now, lets write it to file now
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
        //output xml to console for debugging
        //xmlOutputter.output(doc, System.out);
        xmlOutputter.output(doc, new FileOutputStream(fileName));
    }

}
로그인 후 복사

프로그램을 실행하면 다음과 같은 XML 파일이 생성됩니다:
employees.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee xmlns="" id="1">
    <age>25</age>
    <name>Pankaj</name>
    <gender>Male</gender>
    <role>Java Developer</role>
  </Employee>
  <Employee xmlns="" id="2">
    <age>34</age>
    <name>Mona</name>
    <gender>Female</gender>
    <role>Manager</role>
  </Employee>
  <Employee xmlns="" id="3">
    <age>45</age>
    <name>Dave</name>
    <gender>Male</gender>
    <role>Support</role>
  </Employee></Employees>
로그인 후 복사
로그인 후 복사

원본 주소: http://www.php. cn/

이전 튜토리얼에서는 JDOM을 사용하여 XML 파일의 내용을 구문 분석하고 수정하는 방법을 배웠습니다. 이 섹션에서는 Java 객체를 XML 데이터로 변환하고 파일을 생성하는 방법을 소개합니다.
JDOM의 Document 클래스는 요소와 속성을 생성하는 편리한 방법을 제공합니다. XMLOutputter 클래스는 모든 OutputStream 및 Writer 객체에 Document를 쓸 수 있습니다.
이 예에서는 Employee 개체 컬렉션을 만들고 이를 XML 파일에 씁니다.
Employee.java

package com.journaldev.xml;
public class Employee {    
private int id;    
private String name;    
private String gender;    
private int age;    
private String role;    
public Employee(){}    
public Employee(int id, String name, int age, String gender, String role){        
this.id=id;        
this.age=age;        
this.name=name;        
this.gender=gender;        
this.role=role;
    }    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 String getGender() {        
    return gender;
    }    public void setGender(String gender) {        
    this.gender = gender;
    }    public int getAge() {        
    return age;
    }    public void setAge(int age) {        
    this.age = age;
    }    public String getRole() {        
    return role;
    }    public void setRole(String role) {        
    this.role = role;
    }

}
로그인 후 복사
로그인 후 복사

Employee 개체 ID를 XML 파일의 Employee 요소 속성으로 사용하고 루트 요소 Employees의 네임스페이스를 "http://www.php.php"로 설정합니다. cn/"
JDOMXMLWriter.java

package com.journaldev.xml.jdom;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import org.jdom2.Document;
import org.jdom2.Element;import org.jdom2.Namespace;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import com.journaldev.xml.Employee;
public class JDOMXMLWriter {

    public static void main(String[] args) throws IOException {
        List<Employee> empList = new ArrayList<>();
        empList.add(new Employee(1, "Pankaj",25,"Male","Java Developer"));
        empList.add(new Employee(2, "Mona",34,"Female","Manager"));
        empList.add(new Employee(3, "Dave",45,"Male","Support"));

        String fileName = "employees.xml";
        writeFileUsingJDOM(empList, fileName);
    }

    private static void writeFileUsingJDOM(List<Employee> empList, String fileName) throws IOException {
        Document doc = new Document();
        doc.setRootElement(new Element("Employees",  Namespace.getNamespace("http://www.journaldev.com/employees")));
        for(Employee emp : empList){
            Element employee = new Element("Employee");
            employee.setAttribute("id",""+emp.getId());
            employee.addContent(new Element("age").setText(""+emp.getAge()));
            employee.addContent(new Element("name").setText(emp.getName()));
            employee.addContent(new Element("gender").setText(emp.getGender()));
            employee.addContent(new Element("role").setText(emp.getRole()));
            doc.getRootElement().addContent(employee);
        }
        //JDOM document is ready now, lets write it to file now
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
        //output xml to console for debugging
        //xmlOutputter.output(doc, System.out);
        xmlOutputter.output(doc, new FileOutputStream(fileName));
    }

}
로그인 후 복사

프로그램을 실행하면 다음 XML 파일을 얻을 수 있습니다.
employees.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee xmlns="" id="1">
    <age>25</age>
    <name>Pankaj</name>
    <gender>Male</gender>
    <role>Java Developer</role>
  </Employee>
  <Employee xmlns="" id="2">
    <age>34</age>
    <name>Mona</name>
    <gender>Female</gender>
    <role>Manager</role>
  </Employee>
  <Employee xmlns="" id="3">
    <age>45</age>
    <name>Dave</name>
    <gender>Male</gender>
    <role>Support</role>
  </Employee></Employees>
로그인 후 복사
로그인 후 복사

위는 Java&Xml 튜토리얼의 내용입니다( 8) JDOM을 사용하여 Java 객체를 XML로 변환합니다. 관련 내용을 더 보려면 PHP 중국어 웹사이트(www.php.cn)를 참고하세요!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!