首页 > 代码库 > java生成XML文件
java生成XML文件
java生成XML文件
通过java生成XML文件,在很多场合都会用到。比如:做android应用的时候,有很多数据,都是通过服务端生成的XML文件,再解析XML文件里的数据。
下面是通过JAVA生成XML文件的代码:
import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
/**
* 生成XML文件
***/
public class XmlUtils {
/**
* 根据List列表封装成XML数据
* @return 返回封装后的数据
*/
public static String getXmlFromList(List<User> beanList) {
String result = "";
Element root = new Element("user-list");
Document doc = new Document(root);
for (User user : beanList) {
Element element = new Element("user");
element.addContent(new Element("userId").setText(String.valueOf(user.getUserId())));
element.addContent(new Element("userName").setText(user.getUserName()));
element.addContent(new Element("email").setText(user.getEmail()));
root.addContent(element);
}
XMLOutputter XMLOut = new XMLOutputter();
try {
/**
* 输出XML数据
*/
result = XMLOut.outputString(doc);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
User u1 = new User(1,"张三","");
User u2 = new User(2,"李四","");
User u3 = new User(3,"王五","");
List<User> userList = new ArrayList<User>();
userList.add(u1);
userList.add(u2);
userList.add(u3);
/**
* 根据List数组,生成XML数据
*/
String resultXml = getXmlFromList(userList);
/**
* 打印生成的XML数据
*/
System.out.println(resultXml);
}
}
POJO类:
public class User {
private int userId;
private String userName;
private String email;
public User(int userId, String userName, String email) {
super();
this.userId = userId;
this.userName = userName;
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
生成后的XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<user-list>
<user>
<userId>1</userId>
<userName>张三</userName>
<email>user1@xxx.com</email>
</user>
<user>
<userId>2</userId>
<userName>李四</userName>
<email>user2@xxx.com</email>
</user>
<user>
<userId>3</userId>
<userName>王五</userName>
<email>user3@xxx.com</email>
</user>
</user-list>
备注:其中会用到jdom.jar包。