XML和Java对象互转实现
1、相关对象类
注意注解:
- @XmlRootElement(name = "ROOT")
表示XML的根节点 - @XmlElement(name = "NAME")
表示XML的子节点
package com.MyModel;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ROOT")
public class MyBeanXml {
private String name;
private String id;
private String age;
public String getName() {
return name;
}
@XmlElement(name = "NAME")
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
@XmlElement(name = "ID")
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
@XmlElement(name = "AGE")
public void setAge(String age) {
this.age = age;
}
}
2、测试方法Demo
package com.TestArch;
import com.MyModel.MyBeanXml;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
public class TestXML {
@SneakyThrows
public static void main(String args[]) {
MyBeanXml myBeanXml = new MyBeanXml();
myBeanXml.setAge("28");
myBeanXml.setId("01");
myBeanXml.setName("PHC");
// 对象转 XML System.out.println("----------对象转 XML-------------------");
JAXBContext jaxbContext = JAXBContext.newInstance(MyBeanXml.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(myBeanXml, System.out);
// XML 字符串转对象
String xmlStr = "<ROOT>\n" +
" <AGE>28-Str</AGE>\n" +
" <ID>01-Str</ID>\n" +
" <NAME>PHC-Str</NAME>\n" +
"</ROOT>";
Unmarshaller u = jaxbContext.createUnmarshaller();
StringReader sr = new StringReader(xmlStr);
Object resp = u.unmarshal(sr);
System.out.println("----------XML 字符串转对象-------------------");
System.out.println("" + JSON.toJSONString(resp));
}
}