Java uses jaxb to parse XML (including automatic generation of entity classes based on xml)

Examples of users.xml file

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="1">
        <name>张三</name>
        <age>18</age>
    </user>
    <user id="2">
        <name>李四</name>
        <age>19</age>
    </user>    
</users>

Generate xsd from XML

Put trang.jar and the xml to be parsed in the same directory, execute the following command under the current file, where users.xsd is the name of the xsd file to be generated

java -jar trang.jar users.xml users.xsd

 

trang.jar download address: https://download.csdn.net/download/zheng_chang_wei/10617086

Generate Bean according to xsd

After executing the above command, users.xsd will be generated in the current file, and then execute the following command, where com.bean after -p is the package name, and after -d is the file directory to be generated
 

  xjc -p com.bean users.xsd -d f:


After executing the above command, the entity class will be generated in the F:\com\bean directory

main function

	public static void main(String[] args)  {
		String path = "users.xml";
		try {
			//解析
			Users users = (Users) JaxbUtil.unmarshaller(ObjectFactory.class, path);
			//序列化
			JaxbUtil.marshall(ObjectFactory.class, users, "users2.xml");
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}

JaxbUtil tool class



import java.io.File;
import java.io.FileNotFoundException;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

public class JaxbUtil {

	public static boolean validate(final String xmlPath, final String xsdPath) {
		boolean result = true;
		try {
			final String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
			final SchemaFactory factory = SchemaFactory.newInstance(language);
			final Schema schema = factory.newSchema(new File(xsdPath));
			final Validator validator = schema.newValidator();
			validator.validate(new StreamSource(xmlPath));
		} catch (final Exception e) {
			result = false;
		}
		return result;
	}

	/**
	 * 序列化
	 * @param clazz
	 * @param object
	 * @param path
	 * @throws JAXBException
	 */
	public static void marshall(final Class<?> clazz, final Object object, final String path) throws JAXBException {
		// 通过映射的类创建XMLContext上下文对象,其中参数为映射的类。
		JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
		// 通过JAXBComtext上下文对象的createMarshaller()方法,创建一个对象java格式转化成XML的格式
		Marshaller marshaller = jaxbContext.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		// 最后,将JAVA对象转换到制定的输出位置,其中的object为java对象。
		marshaller.marshal(object, new File(path));
	}

	/**
	 * 解析
	 * @param clazz
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static Object unmarshaller(final Class<?> clazz, final String path) throws Exception {
		if (path == null || !new File(path).exists()) {
			throw new FileNotFoundException();
		}
		// 通过映射的类创建XMLComtext上下文对象,其中参数为映射的类。
		JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
		// 通过JAXBContext上下文对象创建createUnmarshaller()方法,创建XML转换成JAVA对象的格式。
		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		// 最后,将XML转换成对映的类,转换后需要强制性转换成映射的类
		Object object = unmarshaller.unmarshal(new File(path));
		return object;
	}
}

to sum up

Use this method when the xml is more complex to avoid writing complex entity classes by yourself.

Guess you like

Origin blog.csdn.net/zheng_chang_wei/article/details/81903834