Jaxb parses XML and jaxbxml
Traditionally, we use dom4j or jdom to parse xml. Generally, the entire xml is parsed into a document in the memory, and then the document tree is traversed hierarchically, which has the following Disadvantages, the first is memory occupation, and the code is rigid and cannot be parsed for common xml, but Jaxb is different. It can be parsed for any type of xml, even if the xml changes, you can use only a small amount of code without changing the code logic. The specific method is as follows:
1. Generate xsd
First, we generate the corresponding xsdfile according to the existing xmlfile. The corresponding xsd.exe method is provided by Microsoft. We can find this file locally and put the xml file in the same directory of the exe file. For example, our xml file name is resource. xml, then we enter the command line, and then go to the path where the exe file is located, through xsd resource. xml to generate the corresponding resource. xsd, which is the xsd file we need.
2. Generate the corresponding code defined in xsd
Jdk provides an xjc. jar file to convert xsd into the corresponding code. The method is as follows:
xjc –d d:\ –p com.huawei.test resource.xsd
The preceding parameter is defined as follows:-d indicates the path of the xsd file, and-p indicates the package name of the generated code.
3. Read the xml file as an object in the memory.
Assume that we define a Customer in resource. xml, and then we can read the xml into the Customer object in our memory in the following way:
(1) marshal, which generates memory objects in xml:
public void marshalToObject(){ File file = new File("C:\\file1.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(customer, file); jaxbMarshaller.marshal(customer, System.out); }
(2) Unmarshaller: generate an xml file for the objects created in the memory:
public void UnmarshallerToXml(){ File file = new File("C:\\file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); System.out.println(customer); }