1. 程式人生 > >Android 實體類轉xml(JAXB)

Android 實體類轉xml(JAXB)

1,maven上jar包 匯入,可以編譯但是無法通過,懷疑是jar不全。最後換了一個jar包。
一,實體類轉xml

 /**
     * 物件轉xml
     * @param obj
     * @return
     */

    public String  toXml(Object obj){
     String xml=null;
        try {
            JAXBContext jc = JAXBContext.newInstance(TestList.class);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            // 1) 隱去報文頭的生成, Marshaller.JAXB_FRAGMENT預設為false
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            StringWriter writer = new StringWriter();
            // 2) 自定義生成
            writer.write("<gs ver=\"1.0\" function=\"技師資料查詢\" mode=\"request\">\n");
            marshaller.marshal(obj, writer);
            System.out.println(writer.toString()+"\n</gs>");
            xml=writer.toString();
            //XMLEventWriter的類文
        }catch (Exception e){

        }
        return xml;

    }

二,集合類轉XML

  /**
     * 集合
     */
 /**
     *  集合轉xml
     * @param list
     * @return
     */
    public String  toXmlList(List<Object> list){
        String xmlList=null;
        try {
            JAXBContext jc = JAXBContext.newInstance(TestList.class);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            // 1) 隱去報文頭的生成, Marshaller.JAXB_FRAGMENT預設為false
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            StringWriter writer = new StringWriter();
            // 2) 自定義生成
            writer.write("<gs ver=\"1.0\" function=\"技師資料查詢\" mode=\"request\">\n");
            marshaller.marshal(list, writer);
            System.out.println(writer.toString()+"\n</gs>");
            xmlList=writer.toString();
            //XMLEventWriter的類文
        }catch (Exception e){

        }
        return xmlList;

    }

效果:

 
<gs ver="1.0" function="技師資料查詢" mode="request">
<root>
    <listbean>
        <id>1</id>
        <name>小明</name>
        <pwd>123</pwd>
    </listbean>
    <listbean>
        <id>2</id>
        <name>小紅</name>
        <pwd>643</pwd>
    </listbean>
    <listbean>
        <id>1</id>
        <name>小王</name>
        <pwd>2323</pwd>
    </listbean>
    <listbean>
        <id>1</id>
        <name>小陳</name>
        <pwd>2323</pwd>
    </listbean>
</root>
</gs>

Process finished with exit code 0

集合類

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="root")//設定結點名稱。不設定預設是實體類的類名
public class TestList {

    private List<TestBean> listbean;

    public List<TestBean> getListbean() {
        return listbean;
    }

    public void setListbean(List<TestBean> listbean) {
        this.listbean = listbean;
    }
}

這個依賴
implementation ‘javax.xml.stream:stax-api:1.0-2’

jar包地址