packagedemon;importjavax.xml.bind.JAXBContext;importjavax.xml.bind.JAXBException;importjavax.xml.bind.Marshaller;importjavax.xml.bind.Unmarshaller;importjava.io.StringReader;importjava.io.StringWriter;importjava.util.ArrayList;importjava.util.List;/*** Created by mabin6 on 2018/8/31.*/
public classtestMain {public static voidmain(String[] args){
conditions conds= newconditions();
condition cdon= newcondition();
List conlist = new ArrayList<>();
cdon.setBdmbkbh("2");
cdon.setExp("12");
cdon.setFhjgjls("2");
cdon.setNo("1");
cdon.setSid("12");
List sjgliat = new ArrayList<>();
sjgsdw sjdw1= newsjgsdw();
sjdw1.setOperation("=");
sjdw1.setValue("30");
sjgliat.add(sjdw1);
sjgsdw sjdw2= newsjgsdw();
sjdw2.setOperation("1=");
sjdw2.setValue("20");
sjgliat.add(sjdw2);
cdon.setSjgliat(sjgliat);
rxxsd rxsd= newrxxsd();
rxsd.setValue("80");
rxsd.setOperation(">");
cdon.setSjgliat(sjgliat);
cdon.setRxxsd(rxsd);
conlist.add(cdon);
conds.setConlist(conlist);
System.out.println(object2Xml(conds));
}/***@paramxmlStr 字符串
*@paramc 对象Class类型
*@return对象实例*/@SuppressWarnings("unchecked")public static T xml2Object(String xmlStr, Classc) {try{
JAXBContext context=JAXBContext.newInstance(c);
Unmarshaller unmarshaller=context.createUnmarshaller();
T t= (T) unmarshaller.unmarshal(newStringReader(xmlStr));returnt;
}catch(JAXBException e) {
e.printStackTrace();return null;
}
}/***@paramobject 对象
*@return返回xmlStr*/
public staticString object2Xml(Object object) {//这个地方传的是一个对象
try{
StringWriter writer= newStringWriter();
JAXBContext context=JAXBContext.newInstance(object.getClass());
Marshaller marshal=context.createMarshaller();
marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); //格式化输出
marshal.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//编码格式,默认为utf-8
marshal.setProperty(Marshaller.JAXB_FRAGMENT, false);//是否省略xml头信息
marshal.setProperty("jaxb.encoding", "utf-8");
marshal.marshal(object, writer);return newString(writer.getBuffer());
}catch(Exception e) {
e.printStackTrace();return null;
}
}
}