在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文件
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();
}
}