JAXBContext返回生成XML

前端之家收集整理的这篇文章主要介绍了JAXBContext返回生成XML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

用java 生成XML

1,需要的包

javax.xml.bind.jar,jaxb-api.jar,
jaxb-core.jar,
jaxb-impl.jar,
jaxb-jxc.jar,
jaxb-xjc.jar

2,XML中有<!CDATA[]]需要的包

com.springsource.javax.xml.bind-2.2.0.jar,
org.eclipse.persistence.antlr_2.3.0.v20110604-r9504.jar
org.eclipse.persistence.asm_2.3.1.v20110908-r10021.jar
org.eclipse.persistence.core_2.3.0.v20110604-r9504.jar
org.eclipse.persistence.moxy_2.3.1.v20110908-r10021.jar

回复微信消息做实例

public String replay(UserObject text,Class classs) {
		JAXBContext context;
		String xmlObj = null;
		try {
			context = JAXBContext.newInstance(classs);
			Marshaller marshaller = context.createMarshaller(); 
			  marshaller.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
			    // 格式化XML输出,有分行和缩进
			    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
			    // 打印到控制台
			   // marshaller.marshal(text,System.out);
			    marshaller.setProperty(Marshaller.JAXB_FRAGMENT,true);//
			    ByteArrayOutputStream baos = new ByteArrayOutputStream();
			    marshaller.marshal(text,baos);
			try {
				 //  xmlObj = new String(baos.toByteArray());
				xmlObj= baos.toString("utf-8");
				//System.out.println(test);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			   
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  
		 // System.out.println(xmlObj);
		  return xmlObj.replace(" standalone=\"yes\"","");
	}

检查XML实体类

import java.util.Calendar;
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;

@XmlRootElement(name="xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class NewsObject extends UserObject{
	public NewsObject(){
		super.setMsgType("news");
		super.setCreateTime(Calendar.getInstance().getTimeInMillis());
	}
	int ArticleCount;
	 @XmlElementWrapper(name="Articles") 
	 @XmlElement(name="item") 
	List<NewsItem> NewsItems;
	
	
	public List<NewsItem> getNewsItems() {
		return NewsItems;
	}
	public void setNewsItems(List<NewsItem> newsItems) {
		NewsItems = newsItems;
	}
	public int getArticleCount() {
		return ArticleCount;
	}
	public void setArticleCount(int articleCount) {
		ArticleCount = articleCount;
	}
	
}

为了生成CDATA 需要一个 jaxb.properties 文件 需要和需要生成的java类放在同一个目录 javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

猜你在找的XML相关文章