文章目录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.carlos.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;

public class MainActivity extends Activity {

private List<UserInfo> infos;
private UserInfo info;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/**
* 生成List数据给下面生成xml数据使用
*/
crateData();

/**
* 生成xml数据
*/
createXml();

}

void crateData() {
infos = new ArrayList<UserInfo>();
info = new UserInfo();
info.setUsername("Carlos");
info.setAge("21");
infos.add(info);
info = new UserInfo();
info.setUsername("Jack");
info.setAge("19");
infos.add(info);
}

void createXml() {

File file = new File(Environment.getExternalStorageDirectory()+ "/userinfo.xml");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.startTag(null, "root");
for (int i = 0; i < infos.size(); i++) {
info = infos.get(i);
serializer.startTag(null, "userinfo");
serializer.startTag(null, "username");
serializer.text(info.getUsername());
serializer.endTag(null, "username");
serializer.startTag(null, "age");
serializer.text(info.getAge());
serializer.endTag(null, "age");
serializer.endTag(null, "userinfo");
}
serializer.endTag(null, "root");
serializer.endDocument();
serializer.flush();
fos.close();

} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

UserInfo类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.carlos.xml;

public class UserInfo {

private String username;
private String age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}

}

将Android Studio转换到DDMS窗口的File Explorer下可以看到在mnt下的sdcard目录中生成了userinfo.xml文件。

将该文件导出查看生成的XML如下

文章目录