使用jaxb解析xml文件

users.xml文件示例

<?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>

根据XML生成xsd
将trang.jar和要解析的xml放在同一目录,在当前文件下执行如下命令,其中users.xsd为要生成的xsd文件名

java -jar trang.jar(注意名字和当前使用的trang要相同) users.xml users.xsd
    

trang.jar下载地址:https://download.csdn.net/download/zheng_chang_wei/10617086

根据xsd生成Bean
执行完上述命令后会在当前文件生成users.xsd,然后执行如下命令,其中-p后com.bean是包名-d后是要生成到哪的文件目录

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

xjc -p cxy.SVN.LongWayDev_API.src.main.java.org.springblade.modules.fastqv.entity C:\Users\len\Desktop\xmlsc\20211206\LINGQ.xsd -d D:
   
java -Dfile.encoding=UTF-8 -cp "C:\Program Files\Java\jdk1.8.0_40\lib\tools.jar"  com.sun.tools.internal.xjc.Driver -p org.springblade.modules.fastqv.bean.xmlbean C:\Users\len\Desktop\xmlsc\20211206\LIONQ.xsd

执行完上述命令后会在F:\com\bean目录下生成实体类

main函数

	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工具类

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;
	}
}

总结
当xml比较复杂时使用此方法,可避免自己写复杂的实体类。

posted @ 2022-05-12 16:58  xiaomaixiaomai  阅读(398)  评论(0)    收藏  举报