Java使用JAXB对xml的解析和转换

xmlToBean

    /**
     * Convert XML to Bean with Schema Validation.
     *
     * @param entityClass entity Class
     * @param entity      XML
     * @return entity object
     * @throws JAXBException JAXB Exception
     */
    public static <T> Object xmlToBean(Class<T> entityClass, String entity, Schema schema) throws JAXBException {
        Unmarshaller unMarshaller = JAXBContext.newInstance(entityClass).createUnmarshaller();
        unMarshaller.setSchema(schema);
        return unMarshaller.unmarshal(new StringReader(entity));
    }

   

beanToXml

     /**
     * Convert Bean to XML and Validate the XML with Schema.
     *
     * @param entity entity object
     * @return XML
     * @throws JAXBException JAXB Exception
     */
    public static String beanToXml(Marshaller marshaller, Object entity, Schema schema) throws JAXBException {
        StringWriter writer = new StringWriter();
        marshaller.setSchema(schema);
        marshaller.marshal(entity, writer);
        return writer.toString();
    }

    /**
     * Create Marshaller
     *
     * @param entityClass entity object Class
     * @return Marshaller
     * @throws JAXBException JAXB Exception
     */
    public static <T> Marshaller newMarshaller(Class<T> entityClass) throws JAXBException {
        Marshaller marshaller = newJaxbContext(entityClass).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        return marshaller;
    }

Example:

xml to bean

 URL xsdUrl = this.getClass().getResource("xxx.xsd");
 Schema schema = factory.newSchema(xsdUrl);
 Xxbean xxbean = (Xxbean) XmlAndBeanUtil.xmlToBean(Xxbean.class, xmlString, schema);

 

bean to xml

 Marshaller marshaller = XmlAndBeanUtil.newMarshaller(Xxbean.class);
 marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "Xxbean.xsd");
 String xml = XmlAndBeanUtil.beanToXml(marshaller, xxbean, null);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值