我想在使用Dom的Android中生成XML文件,但是當我執行應用程序時,不會生成XML文件,雖然我也沒有收到錯誤。請幫助我。在Android中使用DOM創建XML文件
package com.example.samplexml;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView myTextView;
EditText E1;
EditText E2;
EditText E3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b= (Button) findViewById(R.id.button1);
E1 = (EditText) findViewById(R.id.editText1);
E2 = (EditText) findViewById(R.id.editText2);
E3 = (EditText) findViewById(R.id.editText3);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Class");
doc.appendChild(rootElement);
// staff elements
Element student = doc.createElement("Student");
rootElement.appendChild(student);
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode(E1.getText().toString()));
student.appendChild(firstname);
Element Email = doc.createElement("Email");
Email.appendChild(doc.createTextNode(E2.getText().toString()));
student.appendChild(Email);
// nickname elements
Element Roll = doc.createElement("Roll_No");
Roll.appendChild(doc.createTextNode(E3.getText().toString()));
student.appendChild(Roll);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\f.xml"));
transformer.transform(source, result);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (TransformerException e) {
e.printStackTrace();}
Toast.makeText(getApplicationContext(),
"XML generated", Toast.LENGTH_LONG).show();
}
}); }
}
enter code here
這是什麼, StreamResult result = new StreamResult(new File(「C:\\ f.xml」)); Android上是否存在C:\\? – 2013-04-23 16:50:21
我使用我的系統的C驅動器來存儲文件,同時在模擬器上執行應用程序 – user2044296 2013-04-24 18:58:31
我不認爲你可以使用模擬器訪問計算機的驅動器。 嘗試保存在SD卡上 - 使用getExternalStorageDirectory() – 2013-04-25 06:54:35