1. 程式人生 > 其它 >java解析XML對映成物件實體

java解析XML對映成物件實體

使用JDK自帶的

1.建立一個XML檔案:config.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <root >
 3 
 4     <section target="system_user" description="使用者資訊" relation="" sourceIdentityColumn="id" targetIdentityColumn="source_id" isEnabled="true">
 5         <table source="system_sync_pre_school_student"
description="幼兒園學生資訊" condition="" isEnabled="true"> 6 <column source="id" target="source_id" type="STRING" description="源資料與目標資料的對應值" filter="" replace="" isEnabled="true"/> 7 <column source="name" target="name" type="STRING" description="姓名" filter="" replace=""
isEnabled="true"/> 8 <column source="sex" target="sex" type="STRING" description="性別" filter="" replace="男=1,女=0" isEnabled="true"/> 9 <column source="student_id" target="open_id" type="STRING" description="使用者唯一openId" filter="" replace="" isEnabled="true"/> 10 11
</table> 12 </section> 13 14 <section target="system_user" description="使用者資訊" relation="" sourceIdentityColumn="id" targetIdentityColumn="source_id" isEnabled="true"> 15 <table source="system_sync_pre_school_student" description="幼兒園學生資訊" condition="" isEnabled="true"> 16 <column source="id" target="source_id" type="STRING" description="源資料與目標資料的對應值" filter="" replace="" isEnabled="true"/> 17 <column source="name" target="name" type="STRING" description="姓名" filter="" replace="" isEnabled="true"/> 18 <column source="sex" target="sex" type="STRING" description="性別" filter="" replace="男=1,女=0" isEnabled="true"/> 19 <column source="student_id" target="open_id" type="STRING" description="使用者唯一openId" filter="" replace="" isEnabled="true"/> 20 </table> 21 </section> 22 23 </root>

2.寫一個解析工具類:XMLUtil.java

 1 package org.example.util;
 2 
 3 import javax.xml.bind.JAXBContext;
 4 import javax.xml.bind.JAXBException;
 5 import javax.xml.bind.Marshaller;
 6 import javax.xml.bind.Unmarshaller;
 7 import java.io.*;
 8 
 9 /**
10  * 封裝了XML轉換成object,object轉換成XML的程式碼
11  */
12 public class XMLUtil {
13     /**
14      * 將物件直接轉換成String型別的 XML輸出
15      */
16     public static String convertToXml(Object obj) {
17         // 建立輸出流
18         StringWriter sw = new StringWriter();
19         try {
20             // 利用jdk中自帶的轉換類實現
21             JAXBContext context = JAXBContext.newInstance(obj.getClass());
22             Marshaller marshaller = context.createMarshaller();
23             // 格式化xml輸出的格式
24             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
25                     Boolean.TRUE);
26             marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
27             // 將物件轉換成輸出流形式的xml
28             marshaller.marshal(obj, sw);
29         } catch (JAXBException e) {
30             e.printStackTrace();
31         }
32         return sw.toString();
33     }
34 
35     /**
36      * 將物件根據路徑寫入指定的xml檔案裡
37      * @param obj
38      * @param path
39      * @return
40      */
41     public static void convertToXml(Object obj, String path) {
42         try {
43             // 利用jdk中自帶的轉換類實現
44             JAXBContext context = JAXBContext.newInstance(obj.getClass());
45 
46             Marshaller marshaller = context.createMarshaller();
47             // 格式化xml輸出的格式
48             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
49                     Boolean.TRUE);
50             marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");
51             // 將物件轉換成輸出流形式的xml
52             // 建立輸出流
53             FileWriter fw = null;
54             try {
55                 fw = new FileWriter(path);
56             } catch (IOException e) {
57                 e.printStackTrace();
58             }
59             marshaller.marshal(obj, fw);
60         } catch (JAXBException e) {
61             e.printStackTrace();
62         }
63     }
64 
65     /**
66      * 將String型別的xml轉換成物件
67      */
68     public static Object convertXmlStrToObject(Class<?> clazz, String xmlStr) {
69         Object xmlObject = null;
70         try {
71             JAXBContext context = JAXBContext.newInstance(clazz);
72             // 進行將Xml轉成物件的核心介面
73             Unmarshaller unmarshal = context.createUnmarshaller();
74             StringReader sr = new StringReader(xmlStr);
75             xmlObject = unmarshal.unmarshal(sr);
76         } catch (Exception e) {
77             e.printStackTrace();
78         }
79         return xmlObject;
80     }
81 
82     /**
83      * 將file型別的xml轉換成物件
84      */
85     public static Object convertXmlFileToObject(Class<?> clazz, String xmlPath) {
86         Object xmlObject = null;
87         try {
88             JAXBContext context = JAXBContext.newInstance(clazz);
89             Unmarshaller unmarshaller = context.createUnmarshaller();
90             InputStreamReader isr=new InputStreamReader(new FileInputStream(xmlPath),"UTF-8");
91             xmlObject = unmarshaller.unmarshal(isr);
92         } catch (Exception e) {
93             e.printStackTrace();
94         }
95         return xmlObject;
96     }
97 
98 }

3.按照XML結構,寫出將要對映的實體類:

  1)Root.java

 1 package org.example.entity;
 2 
 3 import lombok.Data;
 4 
 5 import javax.xml.bind.annotation.XmlRootElement;
 6 import java.util.List;
 7 
 8 @Data
 9 //註解用於標記當前類是XML的根節點,name值為根節點名
10 @XmlRootElement(name = "root")
11 public class Root {
12 
13     private List<Section> section;
14 
15 }

  2)Section.java

 1 package org.example.entity;
 2 
 3 import lombok.Setter;
 4 
 5 import javax.xml.bind.annotation.XmlAttribute;
 6 import javax.xml.bind.annotation.XmlTransient;
 7 import java.util.List;
 8 
 9 @Setter 
10 public class Section {
11 
12 
13     @XmlAttribute
14     private String target;
15     @XmlAttribute
16     private String description;
17     @XmlAttribute
18     private String relation;
19     @XmlAttribute
20     private String sourceIdentityColumn;
21     @XmlAttribute
22     private String targetIdentityColumn;
23     @XmlAttribute
24     private boolean isEnabled;
25 
26 
27     private List<Table> table;
28 
29     @XmlTransient
30     public String getTarget() {
31         return target;
32     }
33 
34     @XmlTransient
35     public String getDescription() {
36         return description;
37     }
38 
39     @XmlTransient
40     public String getRelation() {
41         return relation;
42     }
43 
44     @XmlTransient
45     public String getSourceIdentityColumn() {
46         return sourceIdentityColumn;
47     }
48 
49     @XmlTransient
50     public String getTargetIdentityColumn() {
51         return targetIdentityColumn;
52     }
53 
54     @XmlTransient
55     public boolean isEnabled() {
56         return isEnabled;
57     }
58 
59     public List<Table> getTable() {
60         return table;
61     }
62 
63     @Override
64     public String toString() {
65         return "Section{" +
66                 "target='" + target + '\'' +
67                 ", description='" + description + '\'' +
68                 ", relation='" + relation + '\'' +
69                 ", sourceIdentityColumn='" + sourceIdentityColumn + '\'' +
70                 ", targetIdentityColumn='" + targetIdentityColumn + '\'' +
71                 ", isEnabled=" + isEnabled +
72                 ", table=" + table +
73                 '}';
74     }
75 }

  3)Table.java

 1 package org.example.entity;
 2 
 3 import lombok.Setter;
 4 
 5 import javax.xml.bind.annotation.XmlAttribute;
 6 import javax.xml.bind.annotation.XmlTransient;
 7 import java.util.List;
 8 
 9 @Setter
10 public class Table {
11 
12     @XmlAttribute
13     private String source;
14     @XmlAttribute
15     private String description;
16     @XmlAttribute
17     private String condition;
18     @XmlAttribute
19     private boolean isEnabled;
20 
21     private List<Column> column;
22 
23     @XmlTransient
24     public String getSource() {
25         return source;
26     }
27 
28     @XmlTransient
29     public String getDescription() {
30         return description;
31     }
32 
33     @XmlTransient
34     public String getCondition() {
35         return condition;
36     }
37 
38     @XmlTransient
39     public boolean isEnabled() {
40         return isEnabled;
41     }
42 
43     public List<Column> getColumn() {
44         return column;
45     }
46 
47     @Override
48     public String toString() {
49         return "Table{" +
50                 "source='" + source + '\'' +
51                 ", description='" + description + '\'' +
52                 ", condition='" + condition + '\'' +
53                 ", isEnabled=" + isEnabled +
54                 ", column=" + column +
55                 '}';
56     }
57 }

  4)Column.java

 1 package org.example.entity;
 2 
 3 import lombok.Setter;
 4 
 5 import javax.xml.bind.annotation.XmlAttribute;
 6 import javax.xml.bind.annotation.XmlTransient;
 7 
 8 @Setter
 9 public class Column {
10 
11     @XmlAttribute
12     private String source;
13     @XmlAttribute
14     private String target;
15     @XmlAttribute
16     private String type;
17     @XmlAttribute
18     private String description;
19     @XmlAttribute
20     private String filter;
21     @XmlAttribute
22     private String replace;
23     @XmlAttribute
24     private boolean isEnabled;
25 
26     @XmlTransient
27     public String getSource() {
28         return source;
29     }
30 
31     @XmlTransient
32     public String getTarget() {
33         return target;
34     }
35 
36     @XmlTransient
37     public String getType() {
38         return type;
39     }
40 
41     @XmlTransient
42     public String getDescription() {
43         return description;
44     }
45 
46     @XmlTransient
47     public String getFilter() {
48         return filter;
49     }
50 
51     @XmlTransient
52     public String getReplace() {
53         return replace;
54     }
55 
56     @XmlTransient
57     public boolean isEnabled() {
58         return isEnabled;
59     }
60 
61     @Override
62     public String toString() {
63         return "Column{" +
64                 "source='" + source + '\'' +
65                 ", target='" + target + '\'' +
66                 ", type='" + type + '\'' +
67                 ", description='" + description + '\'' +
68                 ", filter='" + filter + '\'' +
69                 ", replace='" + replace + '\'' +
70                 ", isEnabled=" + isEnabled +
71                 '}';
72     }
73 }

4.編寫一個測試類

 1 package org.example;
 2 
 3 import org.example.entity.Root;
 4 import org.example.util.XMLUtil;
 5 
 6 public class Test {
 7 
 8     public static void main(String[] args) {
 9 
10         String path = "config.xml";
11         Root root = (Root) XMLUtil.convertXmlFileToObject(Root.class, path);
12         System.out.println(root);
13 
14     }
15 }

5.檔案結構

  

附:lambok 引用

1     <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
2     <dependency>
3       <groupId>org.projectlombok</groupId>
4       <artifactId>lombok</artifactId>
5       <version>1.18.20</version>
6       <scope>provided</scope>
7     </dependency>
成功不是終點,失敗也並非末日,重要的是前行的勇氣!