xml解析

一.Jaxb处理java对象和xml之间转换常用的annotation有:

  1. @XmlType
  2. @XmlElement
  3. @XmlRootElement
  4. @XmlAttribute
  5. @XmlAccessorType
  6. @XmlAccessorOrder
  7. @XmlTransient
  8. @XmlJavaTypeAdapter

 二.常用annotation使用说明

 

  1. @XmlType

  @XmlType用在class类的注解,常与@XmlRootElement,@XmlAccessorType一起使用。它有三个属性:name、propOrder、namespace,经常使用的只有前两个属性。如:

@XmlType(name = "basicStruct", propOrder = {
    "intValue",
    "stringArray",
    "stringValue"
)
在使用@XmlType的propOrder 属性时,必须列出JavaBean对象中的所有属性,否则会报错。

  2.@XmlElement

  @XmlElement将java对象的属性映射为xml的节点,在使用@XmlElement时,可通过name属性改变java对象属性在xml中显示的名称。如:

  @XmlElement(name="Address")  
  private String yourAddress;

  3.@XmlRootElement

  @XmlRootElement用于类级别的注解,对应xml的跟元素,常与 @XmlType 和 @XmlAccessorType一起使用。如:

  @XmlType
  @XmlAccessorType(XmlAccessType.FIELD)
  @XmlRootElement
  public class Address {}

  4.@XmlAttribute

  @XmlAttribute用于把java对象的属性映射为xml的属性,并可通过name属性为生成的xml属性指定别名。如:
  @XmlAttribute(name="Country")
  private String state;

  5.@XmlAccessorType

  @XmlAccessorType用于指定由java对象生成xml文件时对java对象属性的访问方式。常与@XmlRootElement、@XmlType一起使用。它的属性值是XmlAccessType的4个枚举值,分   别为:

  XmlAccessType.FIELD:java对象中的所有成员变量

  XmlAccessType.PROPERTY:java对象中所有通过getter/setter方式访问的成员变量

  XmlAccessType.PUBLIC_MEMBER:java对象中所有的public访问权限的成员变量和通过getter/setter方式访问的成员变量

  XmlAccessType.NONE:java对象的所有属性都不映射为xml的元素

  注意:@XmlAccessorType的默认访问级别是XmlAccessType.PUBLIC_MEMBER,因此,如果java对象中的private成员变量设置了public权限的getter/setter方法,就不要在   private变量上使用@XmlElement和@XmlAttribute注解,否则在由java对象生成xml时会报同一个属性在java类里存在两次的错误。同理,如果@XmlAccessorType的访问权限   为XmlAccessType.NONE,如果在java的成员变量上使用了@XmlElement或@XmlAttribute注解,这些成员变量依然可以映射到xml文件。

  6.@XmlAccessorOrder

  @XmlAccessorOrder用于对java对象生成的xml元素进行排序。它有两个属性值:

  AccessorOrder.ALPHABETICAL:对生成的xml元素按字母书序排序

  XmlAccessOrder.UNDEFINED:不排序

  7.@XmlTransient

  @XmlTransient用于标示在由java对象映射xml时,忽略此属性。即,在生成的xml文件中不出现此元素。

  8.@XmlJavaTypeAdapter

  @XmlJavaTypeAdapter常用在转换比较复杂的对象时,如map类型或者格式化日期等。使用此注解时,需要自己写一个adapter类继承XmlAdapter抽象类,并实现里面的方法。

  @XmlJavaTypeAdapter(value=xxx.class),value为自己定义的adapter类

  XmlAdapter如下:

     

public abstract class XmlAdapter<ValueType,BoundType> {
    // Do-nothing constructor for the derived classes.
    protected XmlAdapter() {}
    // Convert a value type to a bound type.
    public abstract BoundType unmarshal(ValueType v);
    // Convert a bound type to a value type.
    public abstract ValueType marshal(BoundType v);
 }

  

   三:demo

 

   xml如下:

     

<?xml version="1.0" encoding="UTF-8"?>
<result>
    <status>
        <![CDATA[1]]>
    </status>
    <totalNum>
        <![CDATA[5]]>
    </totalNum>
    <views>
        <view>
            <viewId>
                <![CDATA[gzclss]]>
            </viewId>
            <viewName>
                <![CDATA[长隆水上乐园]]>
            </viewName>
            <cityName>
                <![CDATA[番禺]]>
            </cityName>
            <viewAddress>
                <![CDATA[广州番禺迎宾路长隆旅游度假区 ]]>
            </viewAddress>
            <viewNum>
                <![CDATA[8]]>
            </viewNum>
            <viewLongitude>
                <![CDATA[113.31577]]>
            </viewLongitude>
            <viewLatitude>
                <![CDATA[22.99972]]>
            </viewLatitude>
        </view>
        <view>
            <viewId>
                <![CDATA[hnzwy]]>
            </viewId>
            <viewName>
                <![CDATA[华南植物园]]>
            </viewName>
            <cityName>
                <![CDATA[天河区]]>
            </cityName>
            <viewAddress>
                <![CDATA[广州市天河区兴科路723号]]>
            </viewAddress>
            <viewNum>
                <![CDATA[7]]>
            </viewNum>
            <viewLongitude>
                <![CDATA[113.36001]]>
            </viewLongitude>
            <viewLatitude>
                <![CDATA[23.18487]]>
            </viewLatitude>
        </view>
        <view>
            <viewId>
                <![CDATA[view_28841]]>
            </viewId>
            <viewName>
                <![CDATA[商家测试]]>
            </viewName>
            <cityName>
                <![CDATA[珠海]]>
            </cityName>
            <viewAddress>
                <![CDATA[测试专用]]>
            </viewAddress>
            <viewNum>
                <![CDATA[5]]>
            </viewNum>
            <viewLongitude>
                <![CDATA[]]>
            </viewLongitude>
            <viewLatitude>
                <![CDATA[]]>
            </viewLatitude>
        </view>
        <view>
            <viewId>
                <![CDATA[zygbdst]]>
            </viewId>
            <viewName>
                <![CDATA[中央电视塔]]>
            </viewName>
            <cityName>
                <![CDATA[北京]]>
            </cityName>
            <viewAddress>
                <![CDATA[北京市海淀区西三环中路11号]]>
            </viewAddress>
            <viewNum>
                <![CDATA[3]]>
            </viewNum>
            <viewLongitude>
                <![CDATA[116.29944]]>
            </viewLongitude>
            <viewLatitude>
                <![CDATA[39.91899]]>
            </viewLatitude>
        </view>
        <view>
            <viewId>
                <![CDATA[clyjdw]]>
            </viewId>
            <viewName>
                <![CDATA[长隆野生动物世界(爸爸去哪儿电影拍摄地)]]>
            </viewName>
            <cityName>
                <![CDATA[番禺]]>
            </cityName>
            <viewAddress>
                <![CDATA[广州市番禺区大石镇迎宾路]]>
            </viewAddress>
            <viewNum>
                <![CDATA[3]]>
            </viewNum>
            <viewLongitude>
                <![CDATA[113.32398]]>
            </viewLongitude>
            <viewLatitude>
                <![CDATA[23.00275]]>
            </viewLatitude>
        </view>
    </views>
</result>

   

   分析xml结构可得出,可以设置对应的两个javabean,分别为View.java和ViewInfo.java,代码如下:

    View.java:   

 

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"status" , "totalNum" ,"views"})
@XmlRootElement(name = "result")
public class View {
	@XmlElement(name = "status")
	public String status;
	
	@XmlElement(name = "totalNum")
	public String totalNum;
	
	@XmlElementWrapper(name = "views")//嵌套一层封装好的结合wrapper,xml节点
	@XmlElement(name = "view")//xml节点
	public List<ViewInfo> views;

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(String totalNum) {
		this.totalNum = totalNum;
	}

	public List<ViewInfo> getViews() {
		return views;
	}

	public void setViews(List<ViewInfo> views) {
		this.views = views;
	}
	
}

     ViewInfo.java

   

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"viewId","viewName","cityName","viewAddress","viewNum","viewLongitude","viewLatitude"})
@XmlRootElement(name = "view")
public class ViewInfo {
	@XmlElement(name = "viewId")
	public String viewId;
	
	@XmlElement(name = "viewName")
	public String viewName;
	
	@XmlElement(name = "cityName")
	public String cityName;
	
	@XmlElement(name = "viewAddress")
	public String viewAddress;
	
	@XmlElement(name = "viewNum")
	public String viewNum;
	
	@XmlElement(name = "viewLongitude")
	public String viewLongitude;
	
	@XmlElement(name = "viewLatitude")
	public String viewLatitude;
	
	public String getViewId() {
		return viewId;
	}
	public void setViewId(String viewId) {
		this.viewId = viewId;
	}
	public String getViewName() {
		return viewName;
	}
	public void setViewName(String viewName) {
		this.viewName = viewName;
	}
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	public String getViewAddress() {
		return viewAddress;
	}
	public void setViewAddress(String viewAddress) {
		this.viewAddress = viewAddress;
	}
	public String getViewNum() {
		return viewNum;
	}
	public void setViewNum(String viewNum) {
		this.viewNum = viewNum;
	}
	public String getViewLongitude() {
		return viewLongitude;
	}
	public void setViewLongitude(String viewLongitude) {
		this.viewLongitude = viewLongitude;
	}
	public String getViewLatitude() {
		return viewLatitude;
	}
	public void setViewLatitude(String viewLatitude) {
		this.viewLatitude = viewLatitude;
	}
	
}

   转化工具:ParseUtil.java

  

package com.mangocity.ziwoyou.util;

import java.io.ByteArrayInputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created by zhanghaojia on 14-7-14.
 * ParseUtil工具类主要用于xml解析为Object
 */
public class ParseUtil<T> {
	protected static final Log logger = LogFactory.getLog(ParseUtil.class);
    /**
     * 将xml数据解析成一个Object
     *
     * @param xmlStr 需要解析的xml字符串
     * @param clazz  需要映射到的类
     * @return 解析结果
     */
    @SuppressWarnings("unchecked")
    public T xmlToObject(String xmlStr, Class clazz) {
        JAXBContext jaxbContext = null;
        T obj = null;
        if (xmlStr == null || "nil".equals(xmlStr))
        {
        	return null;
        }
        //logger.info("xmlStr 1 = " + xmlStr);
        try {
        	String fileEncode = System.getProperty("file.encoding");
        	 if (fileEncode != null && fileEncode.equals("GBK")) {
            	 int xml = xmlStr.indexOf("utf-8");
                 if(xml != 0) {
                	 xmlStr = xmlStr.replace("utf-8", "gbk");
                 }
            }
        	//logger.info("xmlStr 2 =|" + xmlStr + "|");
            jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            obj = (T) unmarshaller.unmarshal(new ByteArrayInputStream(xmlStr.getBytes()));
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return obj;
    }
}

   测试:

  

public static void main(String[] args) {
		
		ParseUtil<View> imageListDataParseUtil = new ParseUtil<View>();
        View view =  imageListDataParseUtil.xmlToObject(xml,View.class);
        for (ViewInfo vi : view.getViews()) {
			System.out.println(vi.getCityName());
		}
	}

   结果:

   番禺

   天河区

   珠海

   北京

   番禺

 

 

你可能感兴趣的:(xml解析)