我正在尝试使用 Dom 在 Android 中生成 XML 文件,但是当我执行应用程序时,虽然我也没有收到错误,但没有生成 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