我想在运行时在xml文件中添加带有文本的xml元素(XML文件是 最后还附上了它在包装中的路径)。我的代码要做的是
按下某个按钮时从edittext获取输入
输入文本应作为元素(Item Tag)添加到xml文件中 (pnrstored.xml文件,其目录为packagename / res / Vlaues / pnrstored.xml)
pnrstored.xml在适配器中使用(实际上是字符串数组中的定义)
此adpater已吸引到列表视图
listview应首先显示所有最近添加的值以及之前的值 仅显示必需的代码。
我的问题..以下代码正在更改pnrstored文件..如果我初始化StreamResult结果plz检查该目录时目录中有一些错误..
public class Pnr extends Activity implements OnClickListener{
ArrayAdapter<CharSequence> adapter;
ListView lvSavedPNR;
EditText etPNR;
/* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
adapter = ArrayAdapter.createFromResource(this, R.array.pnrSaved, android.R.layout.simple_list_item_1);
// Specify the layout to use when the list of choices appears
lvSavedPNR.setAdapter(adapter);
somebutton.onclicklisner;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String pnr = etPNR.getEditableText().toString();
savePNR(pnr);
adapter.notifyDataSetChanged();
}
private void savePNR(String pnr2) throws ParserConfigurationException, SAXException, IOException, TransformerException {
// TODO Auto-generated method stub
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("pnrstored.xml");
Element root = document.getDocumentElement();
// Root Element
Element rootElement = document.getDocumentElement();
Collection<Item> svr = new ArrayList<Item>();
svr.add(new Item(pnr));
for (Item i : svr) {
// server elements
Element item = document.createElement("Item");
item.appendChild(document.createTextNode(i.getName()));
rootElement.appendChild(item);
root.appendChild(rootElement);
}
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult ( "pnrstored.xml");
transformer.transform(source, result);
}
public static class Item {
String PNR;
Item(String x){PNR=x;}
public String getName() { return PNR; }
}
包名称/ RES / Vlaues / pnrstored.xml
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<resources>
<string-array name="pnrSaved">
<item>1234567890</item>
</string-array>
</resources>