JAXB:xml与java对象互转
JaxbContext生成xml文件或java类对象转化注解 packagecom.my.test; importjavax.xml.bind.annotation.XmlRootElement; @XmlRootElement publicclassPeople{ publicStringid="22222"; publicStringname="name"; publicintage=26; } Java To XML(Marshal) packagecom.my.test; importjavax.xml.bind.JAXBContext; importjavax.xml.bind.JAXBException; importjavax.xml.bind.Marshaller; publicclassJava2XML{ /** *@paramargs *@throwsJAXBException */ publicstaticvoidmain(String[]args)throwsJAXBException{ JAXBContextcontext=JAXBContext.newInstance(People.class); Marshallermarshaller=context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING,"gb2312");//编码格式 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);//是否格式化生成的xml串 marshaller.setProperty(Marshaller.JAXB_FRAGMENT,false);//是否省略xml头信息(<?xmlversion="1.0"encoding="gb2312"standalone="yes"?>) Peoplepeople=newPeople(); marshaller.marshal(people,System.out); } } XML To Java(UnMarshal) packagecom.my.test; importjava.io.File; importjavax.xml.bind.JAXBContext; importjavax.xml.bind.JAXBException; importjavax.xml.bind.Unmarshaller; importorg.xml.sax.SAXException; publicclassXML2Java{ /** *@paramargs *@throwsJAXBException *@throwsJAXBException *@throwsSAXException */ publicstaticvoidmain(String[]args)throwsJAXBException{ JAXBContextcontext=JAXBContext.newInstance(People.class); Unmarshallerunmarshaller=context.createUnmarshaller(); Filefile=newFile("src/people.xml"); Peoplepeople=(People)unmarshaller.unmarshal(file); System.out.println(people.id); System.out.println(people.name); System.out.println(people.age); } } 其实Marshal 和UnMarshal的过程并不复杂,只需要从JAXBContext中获得Marshaller或Unmarshaller对象,就可以让JAXB帮我们来进行转换了。我们需要操作的主要内容是定义一个规则,告诉JAXB如何将一个类、按照什么样的格式转换为XML。 下面是JAXB中主要的一些注解。 defaultValue 指定节点默认值 name 指定属性名称 propOrder 指定映射XML时的节点顺序factoryClass 指定UnMarshal时生成映射类实例所需的工厂类,默认为这个类本身factoryMethod 指定工厂类的工厂方法name 定义XML Schema中type的名称namespace 指定Schema中的命名空间@XmlElementWrapper 为数组元素或集合元素定义一个父节点。如,类中有一元素为List items,若不加此注解,该元素将被映射为 <items>...</items> <items>...</items> 这种形式,此注解可将这个元素进行包装,如:@XmlElementWrapper(name="items") @XmlElement(name="item") public List items; 将会生成这样的XML样式:<items> <item>...</item> <item>...</item></items> @XmlJavaTypeAdapter 自定义某一字段或属性映射到XML的适配器。如,类中包含一个接口,我们可以定义一个适配器(继承自 javax.xml.bind.annotation.adapters.XmlAdapter类),指定这个接口如何映射到XML。@XmlSchema 配置整个包的namespace,这个注解需放在package-info.java文件中。jaxb编码: JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); InputStreamReader reader=new InputStreamReader(inputStream,"GBK");//在此修改编码 return unmarshaller.unmarshal(reader); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |