将 Java 对象转换为 XML 字符串
要将 Java 对象写入 XML String
,首先要获取 JAXBContext
。
它是 JAXB API 的入口点,并提供解组、编组和验证操作的方法。
现在从 JAXBContext
获取 Marshaller
实例。marshal()
方法将 Java 对象编组为 XML。
现在可以将此 XML 写入不同的输出,例如字符串、文件或者流。
package com.onitroad.demo; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JaxbExample { public static void main(String[] args) { //Java object. We will convert it to XML. Employee employee = new Employee(1, "JackLi", "Gupta", new Department(101, "IT")); //Method which uses JAXB to convert object to XML jaxbObjectToXML(employee); } private static void jaxbObjectToXML(Employee employee) { try { //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); //Create Marshaller Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Required formatting?? jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //Print XML String to Console StringWriter sw = new StringWriter(); //Write XML to StringWriter jaxbMarshaller.marshal(employee, sw); //Verify XML Content String xmlContent = sw.toString(); System.out.println( xmlContent ); } catch (JAXBException e) { e.printStackTrace(); } } }
更多: zhilu jiaocheng
将 Java 对象转换为 XML 文件
我们只需要提供要写入文件的 XML 文件位置。
package com.onitroad.demo; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JaxbExample { public static void main(String[] args) { //Java object. We will convert it to XML. Employee employee = new Employee(1, "JackLi", "Gupta", new Department(101, "IT")); //Method which uses JAXB to convert object to XML jaxbObjectToXML(employee); } private static void jaxbObjectToXML(Employee employee) { try { //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); //Create Marshaller Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Required formatting?? jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //Store XML to File File file = new File("employee.xml"); //Writes XML file to file-system jaxbMarshaller.marshal(employee, file); } catch (JAXBException e) { e.printStackTrace(); } } }
Java 读取 XML 示例
如果我们想再次将 XML 从文件读取到 Java 对象,则使用此方法。
String fileName = "employee.xml"; //Call method which read the XML file above jaxbXmlFileToObject(fileName); private static void jaxbXmlFileToObject(String fileName) { File xmlFile = new File(fileName); JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile); System.out.println(employee); } catch (JAXBException e) { e.printStackTrace(); } }
日期:2020-09-17 00:09:29 来源:oir作者:oir