如何将 xml 写入原始目录中的文件。我几乎完成了一切,只需要这最后一步。
XmlSerializer xmlWriter = Xml.newSerializer();
StringWriter writer = new StringWriter();
String namespace = "";
try{
xmlWriter.setOutput(writer);
xmlWriter.startDocument("UTF-8", true);
xmlWriter.startTag("", "contacts");
xmlWriter.startTag("", "entry");
xmlWriter.attribute("", "entry", "String");
for (int i = 0; i < sortedList.size(); i++){
xmlWriter.startTag("", "firstname");
xmlWriter.text(sortedList.get(i).getFirstName());
xmlWriter.endTag(namespace, "firstname" );
xmlWriter.startTag(namespace, "lastname");
xmlWriter.text(sortedList.get(i).getLastName());
xmlWriter.endTag(namespace, "lastname");
xmlWriter.startTag(namespace, "number");
xmlWriter.text(sortedList.get(i).getPhoneNumber());
xmlWriter.endTag(namespace, "number");
}
xmlWriter.endTag(namespace, "entry");
xmlWriter.endTag(namespace, "contacts");
xmlWriter.endDocument();
xmlWriter.setOutput(writer);
// Write to res/raw/contacts.xml
作者将所有 xml 格式正确并按我想要的方式排序。我只需要弄清楚如何将其写入我的 res/raw 文件夹中的文件。
编辑 我正在使用 XmlPullParser 和 InputStream 读取文件:
XmlPullParser xmlData;
InputStream input = context.getResources().openRawResource(R.raw.contacts);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
xmlData = factory.newPullParser();
xmlData.setInput(input, "UTF-8");
谢谢