java使用jaxb解析XML(含根據xml自動生成實體類)
阿新 • • 發佈:2019-01-30
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 users.xml users.xsd
根據xsd生成Bean
執行完上述命令後會在當前檔案生成users.xsd,然後執行如下命令,其中-p後com.bean是包名,-d後是要生成到哪的檔案目錄
xjc -p com.bean users.xsd -d f:
執行完上述命令後會在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比較複雜時使用此方法,可避免自己寫複雜的實體類。