JAXB解析XML为对象

JAXB支持注解将XML转化为对象,具体看一个简单的例子:

<?xml version="1.0" encoding="utf-8"?>
<Api> 
  <algos> 
    <!-- 算法类型 -->  
    <algo name="YYFY" text="运营费用">
    </algo> 
  </algos>  
</Api>

  XML对应的pojo对象:

package com.yss.aval.aa.util.pojo;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 * AlgoAPI.xml封装对象
 * 此对象仅供解析XML封装数据临时使用
 * 
 * 
 */

@XmlRootElement(name = "Api")
public class AlgoAPIU {

	/**
	 * 对应节点 algos
	 */
	@XmlElement(name = "algos")
	private AlgosU algos;

	@XmlTransient
	public AlgosU getAlgos() {
		return algos;
	}

	public void setAlgos(AlgosU algos) {
		this.algos = algos;
	}

}

  

package com.yss.aval.aa.util.pojo;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 * 对应algos节点
 * 此对象仅供解析XML封装数据临时使用
 * 
 *
 */
public class AlgosU {
	@XmlElement(name = "algo")
	private List<AlgoU> list;

	@XmlTransient
	public List<AlgoU> getList() {
		return list;
	}

	public void setList(List<AlgoU> list) {
		this.list = list;
	}
}

  

package com.yss.aval.aa.util.pojo;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 * 对应AlgoAPI.xml节点的algo
 * 此对象仅供解析XML封装数据临时使用
 * 
 * 
 */
public class AlgoU {

	@XmlAttribute(name = "name")
	private String name;

	@XmlAttribute(name = "text")
	private String text;
	
	@XmlElement(name="variables")
	private VariableAPIU variableAPI;
	
	

	@XmlTransient
	public VariableAPIU getVariableAPI() {
		return variableAPI;
	}

	public void setVariableAPI(VariableAPIU variableAPI) {
		this.variableAPI = variableAPI;
	}

	@XmlTransient
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@XmlTransient
	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	
}

  测试类:

package com.yss.aval.aa.util;

import java.io.File;

import com.yss.aval.aa.util.pojo.AlgoAPIU;
import com.yss.framework.api.util.JAXBProcessor;

/**
 * AlgoAPI.xml解析工具类
 * 
 * 
 * @Date 20170712
 */
public class AlgoAPIXMLParse {

	/**
	 * 加载并解析AlgoApi.xml
	 */
	public static AlgoAPIU load() {
		JAXBProcessor jProc;

		try {
			jProc = new JAXBProcessor();
			AlgoAPIU algoAPI = new AlgoAPIU();
			algoAPI = (AlgoAPIU) jProc.unMarshal(algoAPI, new File(
					"D:/AlgoApi.xml"));
			return algoAPI;
		} catch (Exception e) {
			e.getStackTrace();
		}
		
		return null;
	}

	/*
	 * public static void main(String[] args) { AlgoAPIXMLParse api = new
	 * AlgoAPIXMLParse(); api.load(); }
	 */
}

  特别注意的是 XML的没一个节点对应一个对象。

posted @ 2017-07-14 10:48  xfma  阅读(568)  评论(0编辑  收藏  举报