Java教程

XML和Java对象互转实现

本文主要是介绍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));  
    }  
}

3、输出结果

附:代码在GitHub的提交

1、XML和对象的相关转换; · NullTommy/hello@cac3504

这篇关于XML和Java对象互转实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!