如何将xml文件转变成java对象

1.xml文件,下面是我要解析的xml文件

<?xml version="1.0" encoding="utf-8"?>
<config>
    <!-- 生成分类 -->
    <category>
        <category value="curd" label="增删改查(单表)">
            <template>curd/controller.xml</template>
            <template>curd/restController.xml</template>
            <template>curd/service.xml</template>
            <template>category-ref:dao</template>
            <template>curd/viewForm.xml</template>
            <template>curd/viewList.xml</template>
        </category>
        <category value="curd_many" label="增删改查(一对多)">
            <template>curd/controller.xml</template>
            <template>curd/restController.xml</template>
            <template>curd/serviceMany.xml</template>
            <template>category-ref:dao</template>
            <template>curd/viewFormMany.xml</template>
            <template>curd/viewList.xml</template>
            <childTable>
                <template>category-ref:dao</template>
            </childTable>
        </category>
        <category value="dao" label="仅持久层(dao/entity/mapper)">
            <template>dao/dao.xml</template>
            <template>dao/entity.xml</template>
            <template>dao/mapper.xml</template>
        </category>
        <category value="treeTable" label="树结构表(一体)">
            <template>treetable/controller.xml</template>
            <template>treetable/restController.xml</template>
            <template>treetable/service.xml</template>
            <template>treetable/dao.xml</template>
            <template>treetable/entity.xml</template>
            <template>treetable/mapper.xml</template>
            <template>treetable/viewForm.xml</template>
            <template>treetable/viewList.xml</template>
        </category>
        <category value="treeTableAndList" label="树结构表(左树右表)">
            <template>category-ref:dao</template>
        </category>
    </category>
    <!-- java类型 -->
    <javaType>
        <dict value="String" label="String"/>
        <dict value="Long" label="Long"/>
        <dict value="Integer" label="Integer"/>
        <dict value="Double" label="Double"/>
        <dict value="java.util.Date" label="Date"/>
        <dict value="com.m2plat.his.modules.sys.entity.User" label="User"/>
        <dict value="com.m2plat.his.modules.sys.entity.Office" label="Office"/>
        <dict value="com.m2plat.his.modules.sys.entity.Area" label="Area"/>
        <dict value="This" label="ThisObj" description="生成当前对象"/>
        <dict value="Custom" label="Custom" description="自定义对象,生成后手动设置"/>
    </javaType>
    <!-- 查询类型 -->
    <queryType>
        <dict value="=" label="="/>
        <dict value="!=" label="!="/>
        <dict value="&gt;" label="&gt;"/>
        <dict value="&gt;=" label="&gt;="/>
        <dict value="&lt;" label="&lt;"/>
        <dict value="&lt;=" label="&lt;="/>
        <dict value="between" label="Between"/>
        <dict value="like" label="Like"/>
        <dict value="left_like" label="Left Like"/>
        <dict value="right_like" label="Right Like"/>
    </queryType>
    <!-- 字段显示类型 -->
    <showType>
        <dict value="input" label="单行文本"/>
        <dict value="textarea" label="多行文本"/>
        <dict value="select" label="下拉选项"/>
        <dict value="radiobox" label="单选按钮"/>
        <dict value="checkbox" label="复选框"/>
        <dict value="dateselect" label="日期选择"/>
        <dict value="userselect" label="人员选择"/>
        <dict value="officeselect" label="部门选择"/>
        <dict value="areaselect" label="区域选择"/>
        <dict value="treeselect" label="树选择控件"/>
        <dict value="fileselect" label="文件上传选择"/>
    </showType>
</config>

2.然后建一个解析的对象类

@XmlRootElement(name="config")
public class GenConfig implements Serializable {

    private static final long serialVersionUID = 1L;
    private List<GenCategory> categoryList; // 代码模板分类
    private List<Dict> javaTypeList;        // Java类型
    private List<Dict> queryTypeList;       // 查询类型
    private List<Dict> showTypeList;        // 显示类型

    public GenConfig() {
        super();
    }

    @XmlElementWrapper(name = "category")
    @XmlElement(name = "category")
    public List<GenCategory> getCategoryList() {
        return categoryList;
    }

    public void setCategoryList(List<GenCategory> categoryList) {
        this.categoryList = categoryList;
    }

    @XmlElementWrapper(name = "javaType")
    @XmlElement(name = "dict")
    public List<Dict> getJavaTypeList() {
        return javaTypeList;
    }

    public void setJavaTypeList(List<Dict> javaTypeList) {
        this.javaTypeList = javaTypeList;
    }

    @XmlElementWrapper(name = "queryType")
    @XmlElement(name = "dict")
    public List<Dict> getQueryTypeList() {
        return queryTypeList;
    }

    public void setQueryTypeList(List<Dict> queryTypeList) {
        this.queryTypeList = queryTypeList;
    }

    @XmlElementWrapper(name = "showType")
    @XmlElement(name = "dict")
    public List<Dict> getShowTypeList() {
        return showTypeList;
    }

    public void setShowTypeList(List<Dict> showTypeList) {
        this.showTypeList = showTypeList;
    }

}

其中GenCategory 类

@XmlRootElement(name="category")
public class GenCategory extends Dict {

    private static final long serialVersionUID = 1L;
    private List<String> template;          // 主表模板
    private List<String> childTableTemplate;// 子表模板

    public static String CATEGORY_REF = "category-ref:";

    public GenCategory() {
        super();
    }

    @XmlElement(name = "template")
    public List<String> getTemplate() {
        return template;
    }

    public void setTemplate(List<String> template) {
        this.template = template;
    }

    @XmlElementWrapper(name = "childTable")
    @XmlElement(name = "template")
    public List<String> getChildTableTemplate() {
        return childTableTemplate;
    }

    public void setChildTableTemplate(List<String> childTableTemplate) {
        this.childTableTemplate = childTableTemplate;
    }

}

Dict类

public class Dict extends DataEntity<Dict> {

    private static final long serialVersionUID = 1L;
    private String value;   // 数据值
    private String label;   // 标签名
    private String type;    // 类型
    private String description;// 描述
    private Integer sort;   // 排序
    private String parentId;//父Id

    public Dict() {
        super();
        this.isNewRecord=true;//ID采用自增长
    }

    public Dict(String id){
        super(id);
        this.isNewRecord=true;//ID采用自增长
    }

    public Dict(String value, String label){
        this.value = value;
        this.label = label;
        this.isNewRecord=true;//ID采用自增长
    }

    @XmlAttribute
    @Length(min=1, max=100)
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @XmlAttribute
    @Length(min=1, max=100)
    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    @Length(min=1, max=100)
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @XmlAttribute
    @Length(min=0, max=100)
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @NotNull
    public Integer getSort() {
        return sort;
    }

    public void setSort(Integer sort) {
        this.sort = sort;
    }

    @Length(min=1, max=100)
    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    @Override
    public String toString() {
        return label;
    }
}

其中@XmlAttribute:该属性作为xml的attribute
XML转化成对象

public static <T> T fileToObject(String fileName, Class<?> clazz){
        try {
            String pathName = "/templates/modules/gen/" + fileName;
            logger.debug("File to object: {}", pathName);
            Resource resource = new ClassPathResource(pathName);
            InputStream is = resource.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder sb = new StringBuilder();  
            while (true) {
                String line = br.readLine();
                if (line == null){
                    break;
                }
                sb.append(line).append("\r\n");
            }
            if (is != null) {
                is.close();
            }
            if (br != null) {
                br.close();
            }
            return (T) JaxbMapper.fromXml(sb.toString(), clazz);
        } catch (IOException e) {
            logger.warn("Error file convert: {}", e.getMessage(),e);
        }
        return null;
    }

其中JaxbMapper.fromXml(sb.toString(), clazz)代码

public static <T> T fromXml(String xml, Class<T> clazz) {
        try {
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller(clazz).unmarshal(reader);
        } catch (JAXBException e) {
            throw Exceptions.unchecked(e);
        }
    }

调用方法

public static GenConfig getConfig(){
        return fileToObject("config.xml", GenConfig.class);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值