package B.Unit;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.List;
import org.xmlpull.v1.XmlSerializer;
import android.os.Environment;
import android.util.Xml;
public class SaxWriteXml {
public String writeUserInfoToString(Listusers) {
// 实现xml信息序列化的一个对象
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
// xml数据经过序列化后保存到String中,然后将字符串通过OutputStream保存为xml文件
serializer.setOutput(writer);
// 文档开始
serializer.startDocument("utf-8", true);
// 开始一个节点
serializer.startTag("", "users");
// 开始一个子节点
for (User user : users) {
serializer.startTag("", "user");
serializer
.attribute("", "id", String.valueOf(user.getUserId()));
serializer.startTag("", "name");
serializer.text(user.getUserName());
serializer.endTag("", "name");
serializer.startTag("", "pwd");
serializer.text(user.getPassword());
serializer.endTag("", "pwd");
serializer.startTag("", "info");
serializer.text(String.valueOf(user.getInfo()));
serializer.endTag("", "info");
serializer.endTag("", "user");
}
serializer.endTag("", "users");
// 关闭文档
serializer.endDocument();
} catch (Exception e) {
e.printStackTrace();
}
return writer.toString();
}
public boolean writeToXml( String str,String filePat) {
System.out.println("run==>writeToXml");
OutputStream out = null;
try {
String dirPath = Environment.getExternalStorageDirectory()
.toString() + "/xml";
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdir();
File f = new File(dirPath +"/"+ filePat);
System.out.println(dirPath +"/"+ filePat);
out = new FileOutputStream(f);
} catch (Exception e) {
System.out.println("Error"+e.getMessage());
return false;
}
OutputStreamWriter outw = new OutputStreamWriter(out);
try {
outw.write(str);
outw.close();
out.close();
} catch (Exception e) {
return false;
}
return true;
}
}