当前位置: 代码迷 >> J2SE >> xml 转 bean 的有关问题,
  详细解决方案

xml 转 bean 的有关问题,

热度:61   发布时间:2016-04-24 01:08:35.0
xml 转 bean 的问题,求助。。。。。。
要转换的xml
XML code
<?xml version="1.0" encoding="UTF-8"?><User>    <Age>23</Age>    <NameList>        <name>name1</name>        <name>name2</name>        <name>name3</name>        <name>name4</name>            </NameList></User>


对应的 User 类

Java code
public class User {        private int age;        private List nameList;}


请问:对于这样的xml转换成bean 用apache 的 simpleXml 该怎样实现呢? 谢谢!

------解决方案--------------------
推荐用dom4j来解析xml,这个不难,更多信息请百度
------解决方案--------------------
Java code
            File file= new File(xmlFileName);            DocumentBuilderFactory ch =                                 DocumentBuilderFactory.newInstance();            DocumentBuilder db = ch.newDocumentBuilder() ;            Document dom = db.parse(file) ;            NodeList nl_sr = dom.getElementsByTagName("source-rightCode");
------解决方案--------------------
其实就是解析xml文件,然后赋值给你的bean对象。

用什么解析方式得看你的具体需求
------解决方案--------------------
Java code
import com.thoughtworks.xstream.*;import com.google.common.io.*;import com.google.common.base.*;public class Main {    public static void main(final String[] args) throws Exception{        XStream xstream = new XStream();        xstream.alias("User",User.class);        xstream.aliasField("Age",User.class,"age");        xstream.aliasField("NameList",User.class,"nameList");        xstream.alias("name",String.class);                User user = (User)xstream.fromXML(Resources.toString(Resources.getResource(Main.class,"user.xml"),Charsets.UTF_8));        System.out.println(xstream.toXML(user));    }}
------解决方案--------------------
最后一句的输出是
XML code
<User>  <Age>23</Age>  <NameList>    <name>name1</name>    <name>name2</name>    <name>name3</name>    <name>name4</name>  </NameList></User>
------解决方案--------------------
simple-xml 的话

Java code
@ElementList(name="NameList",entry="name")private List<String> nameList;
------解决方案--------------------
xstream 也有 annotation ,功能好像比api弱多了。

Java code
@XStreamAlias("Age")private int age;
  相关解决方案