用java 生成XMLjava
1,須要的包spring
javax.xml.bind.jar, jaxb-api.jar, jaxb-core.jar, jaxb-impl.jar, jaxb-jxc.jar, jaxb-xjc.jar
2,XML中有<!CDATA[]]須要的包api
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實體類app
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.JAXBContextFactoryeclipse