日期:2014-05-20 浏览次数:20683 次
<?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>
public class User { private int age; private List nameList; }
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对象。
用什么解析方式得看你的具体需求
------解决方案--------------------
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)); } }
------解决方案--------------------
最后一句的输出是
<User> <Age>23</Age> <NameList> <name>name1</name> <name>name2</name> <name>name3</name> <name>name4</name> </NameList> </User>
------解决方案--------------------
simple-xml 的话
@ElementList(name="NameList",entry="name") private List<String> nameList;
------解决方案--------------------
xstream 也有 annotation ,功能好像比api弱多了。
@XStreamAlias("Age") private int age;