在Android開發中經常遇到組裝xml格式數據的需求,下面是解決方法,希望給大家帶來幫助。
下面這段xml文件內容是我們的需求。
<?xml version='1.0' encoding='utf-8' standalone='no' ?>
<persons>
<person key="one">
<name>zhangsan</name>
<age>26</age>
</person>
<person key="two">
<name>lisi</name>
<age>25</age>
</person>
</persons>
下面是組裝xml文件內容的代碼。關於如何解析xml文件,請參見這篇:使用SAX解析XML文件 http://www.linuxidc.com/Linux/2013-02/79505.htm
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import java.io.IOException;
import java.io.StringWriter;
public class MainActivity extends Activity {
public static final String TAG = "MainActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, createXMLData());
}
/**
* create xml data
*
* @return
*/
protected String createXMLData() {
XmlSerializer serializer = Xml.newSerializer();
StringWriter stringWriter = new StringWriter();
try {
serializer.setOutput(stringWriter);
serializer.startDocument("utf-8", false);
// start persons
serializer.startTag(null, "persons");
// one
serializer.startTag(null, "person");
serializer.attribute(null, "key", "one");
serializer.startTag(null, "name");
serializer.text("zhangsan");
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text("26");
serializer.endTag(null, "age");
serializer.endTag(null, "person");
// two
serializer.startTag(null, "person");
serializer.attribute(null, "key", "two");
serializer.startTag(null, "name");
serializer.text("lisi");
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text("25");
serializer.endTag(null, "age");
serializer.endTag(null, "person");
// end persons
serializer.endTag(null, "persons");
serializer.endDocument();
} catch (IOException e) {
e.printStackTrace();
}
return stringWriter.toString();
}
}
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11