android 读写xml,修改appserver.xml(根据appserver.xml文件的位置进行操作)

这个例子可以独立运行,需要在res/xml中添加一个appserver.xml文件。

package com.capinfo.mobile.elena_wang;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.capinfo.mobile.R;
import com.capinfo.mobile.application.AppServerVO;
import com.capinfo.mobile.base.view.NewLockActivity;
import com.capinfo.mobile.exception.MSCException;
import com.capinfo.mobile.utils.MSCUtil;
import com.capinfo.mobilecore.utils.CoreConstants;


public class SystemVersionAppserver extends Activity {

	ListView listview;//显示AppServer中内容
	List<HashMap<String, Object>> list = null;//直接解析appserver.xml得到的内容
	List<HashMap<String, Object>> listTitle = null;//存储更改的listview中的内容
	
	boolean[] isChange;//判断是否修改了值
	private SimpleAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appserver);
		setTitle("appserver");//设置页面的title
		
		listview = (ListView)findViewById(R.id.appserver_listview);
		
		list = new ArrayList<HashMap<String, Object>>();
		listTitle  = new ArrayList<HashMap<String, Object>>();
		
		File file = new File(CoreConstants.FILE_SYSTEM_PATH + "appserver.xml");//获取sdcard上的文件路径
		//判断sdcard中是否有AppServer.xml文件
		if (!file.exists()) {//证明sdcard中没有该资源文件。
			getAppServer(SystemVersionAppserver.this.getResources().getXml(R.xml.appserver));
			System.out.println("sdcard中没有资源文件");
			saveUpdate();//往sdcard中写入appserver.xml文件。
		} else {//sdcard上面有资源文件,则直接解析sdcard上的文件
			pullXml();
		}
		
		adapter = new SimpleAdapter(this, listTitle,
				R.layout.appserver_list, new String[] { "appName",
						"appValue" }, new int[] {
						R.id.appserver_list_tv,
						R.id.appserver_list_et });
		listview.setAdapter(adapter);
		
		listview.setOnItemClickListener(listener);

		isChange = new boolean[list.size()];//初始化isChange,先赋值为false
		for(int i = 0;i<list.size();i++){
			isChange[i] = false;
		}

	}//end onCreate()

	/**listview监听item事件 
	 *
	 * @author elena*/
	private OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View arg1, final int arg2,
				long arg3) {
			
			HashMap<String, Object> map = listTitle.get(arg2);
			final String appValue = map.get("appValue").toString();
			
			final EditText et = new EditText(SystemVersionAppserver.this);
			et.setText(appValue);
			et.setSingleLine(); // 设置单行显示
			et.setGravity(Gravity.FILL_HORIZONTAL); // 使对话框位于屏幕的底部并居中
			et.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 100));
			
			final String appName = map.get("appName").toString();

			AlertDialog dialog = new AlertDialog.Builder(SystemVersionAppserver.this).setTitle(appName).setView(et)
					.setPositiveButton("确定", // 确定按钮
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									String value_2 = et.getText().toString();
									HashMap<String, Object> map = new HashMap<String, Object>();
									map.put("appName", appName);
									map.put("appValue", value_2);
									listTitle.set(arg2, map);
									adapter.notifyDataSetChanged();// 更新listview
									dialog.cancel();
									change(arg2);//判断是否改变list中的内容是否改变了
								}
							}).setNegativeButton("取消", // 取消按钮
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
									dialog.dismiss();
								}
							}).create();
			dialog.show();
			
		}
	};
	
	/**提示对话框,是否保存  
	 * 
	 * @author elena*/
	public void showDialog() {
		AlertDialog dialog = new AlertDialog.Builder(
				SystemVersionAppserver.this)
				.setTitle("是否确定保存修改的内容")
				.setPositiveButton(R.string.main_b_submit,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(
									DialogInterface paramDialogInterface,
									int paramInt) {
								saveUpdate();
								SystemVersionAppserver.this.finish();
								System.out.println("=======change===saveUpdate===");
							}
						})
				.setNegativeButton(R.string.main_b_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int arg1) {
								System.out.println("=======change===cancel======");
								dialog.cancel();
								SystemVersionAppserver.this.finish();
							}
						}).create();
		dialog.show();
	}//end showDialog()

	/**判断是否修改,修改了之后在退出时弹出对话框是否确定保存  
	 * 
	 * @author 王晨
	 */
	private void change(int position) {
		String b = listTitle.get(position).get("appValue").toString();
		if(!(list.get(position).get("appValue").toString()).equals(b)){
			isChange[position] = true;
			//System.out.println("====change position is===="+position);
		}else{
			isChange[position] = false;
		}
	}//end change()
	
	/**
	 * 解析SDcard文件函数 
	 * 
	 * @author elena
	 */
	private void pullXml() {
		list.clear();
		listTitle.clear();
		String path = CoreConstants.FILE_SYSTEM_PATH + "appserver.xml";
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(path), "UTF-8");

			int type = parser.getEventType();// 获取事件类型
			while (type != XmlPullParser.END_DOCUMENT) {
				if (type == XmlPullParser.START_TAG) {
					String tagName = parser.getName();
					if (tagName.equals("app")) {
						HashMap<String, Object> map = new HashMap<String, Object>();
						String appName = parser.getAttributeValue(0);
						map.put("appName", appName);
						String appValue = parser.getAttributeValue(1);
						map.put("appValue", appValue);
						list.add(map);
						listTitle.add(map);
					}
				}
				type = parser.next();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}//end pullxml()

	/** 保存修改后的内容
	 * 
	 * @author elena */
	public void saveUpdate() {
		System.out.println("===------save  update-------====");
		StringBuffer str = new StringBuffer();
		str.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
				+ "<resources>");
		for(int i = 0;i<listTitle.size();i++){
			String a = listTitle.get(i).get("appName").toString();
			String b = listTitle.get(i).get("appValue").toString();
			b = b.replace("&", "&");//将b中含有“&”的位置改为“&”的方法用后面的字符串代替前面的字符串
			str.append(" <app ").append("id=\""+a+"\" ").append("value=\""+b+"\" ").append("/>");
		}	
		str.append("</resources>");

		String file_path = CoreConstants.FILE_SYSTEM_PATH + "appserver.xml";
		File file = new File(file_path);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			fos.write(str.toString().getBytes());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}//end saveUpdate()
	
	/**
	 * 读取res/xml下资源文件
	 * 
	 * @author elena
	 * 
	 * @param xrp
	 *            XmlResourceParser
	 * @return 服务器信息
	 */
	public void getAppServer(final XmlResourceParser xrp) {
		try {
			list.clear();
			listTitle.clear();
			
			while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
				if (xrp.getEventType() == XmlResourceParser.START_TAG) {
					String s = xrp.getName();

					if (s.equals("app")) {
						String id = xrp.getAttributeValue(null, "id");
						String value = xrp.getAttributeValue(null, "value");
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("appName", id);
						map.put("appValue", value);
						list.add(map);
						listTitle.add(map);
					}
				}
				xrp.next();
			}
		} catch (Exception e) {
			MSCException.show("Constants.getAppServer error ! ", e);
		} finally {
			xrp.close();
		}
	}

	/**
	 * 捕捉返回按钮事件
	 * 
	 * @author elena
	 * 
	 * @param keyCode
	 *            按键编码
	 * @param event
	 *            按键事件
	 * @return true
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 是否触发按键为back键
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			for(int i=0;i<list.size();i++){
				if(isChange[i] == true){
					showDialog();
					return true;
				}
			}
			return super.onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
		
	}
	
}

xml文件操作 public class XmlUtils { /** * 获取Document对象。根据xml文件的名字获取Document对象。 * * @param file * 要获取对象的xml文件全路径。 * @return 返回获取到的Document对象。 * @throws IOException * 如果发生任何 IO 错误时抛出此异常。 * @throws SAXException * 如果发生任何解析错误时抛出此异常。 * @throws ParserConfigurationException * 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。 * @exception NullPointerException * 如果file为空时,抛出此异常。 */ public static Document parseForDoc(final String file) throws SAXException, IOException, SecurityException, NullPointerException, ParserConfigurationException { return XmlUtils.parseForDoc(new FileInputStream(file)); } /** * 将一个xml字符串解析成Document对象。 * * @param xmlStr * 要被解析的xml字符串。 * @param encoding * 字符串的编码。 * @return 返回解析后的Document对象。 * @throws IOException * 如果发生任何 IO 错误时抛出此异常。 * @throws SAXException * 如果发生任何解析错误时抛出此异常。 * @throws ParserConfigurationException * 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。 */ public static Document parseForDoc(String xmlStr, String encoding) throws SAXException, IOException, ParserConfigurationException { if (xmlStr == null) { xmlStr = ""; } ByteArrayInputStream byteInputStream = new ByteArrayInputStream( xmlStr.getBytes(encoding)); return XmlUtils.parseForDoc(byteInputStream); } /** * 获取Document对象。根据字节输入流获取一个Document对象。 * * @param is * 获取对象的字节输入流。 * @return 返回获取到的Document对象。如果出现异常,返回null。 * @throws IOException * 如果发生任何 IO 错误时抛出此异常。 * @throws SAXException * 如果发生任何解析错误时抛出此异常。 * @throws ParserConfigurationException * 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。 * @exception IllegalArgumentException * 当 is 为 null 时抛出此异常。 */ public static Document parseForDoc(final InputStream is) throws SAXException, IOException, ParserConfigurationException, IllegalArgumentException { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(is); } finally { is.close(); } } /** * 通过xpath表达式解析某个xml节点。 * * @param obj * 要被解析的xml节点对象。 * @param xPath * xpath表达式。 * @param qName * 被解析的目标类型。 * @return 返回解析后的对象。 * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ private static Object parseByXpath(final Object obj, final String xPath, QName qName) throws NullPointerException, RuntimeException, XPathExpressionException { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath path = xpathFactory.newXPath(); return path.evaluate(xPath, obj, qName); } /** * 通过XPath表达式获取单个节点。 * * @param obj * 要被解析的對象。 * @param xPath * XPath表达式。 * @return 返回获取到的节点。 * * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ public static Node parseForNode(final Object obj, final String xPath) throws NullPointerException, RuntimeException, XPathExpressionException { return (Node) XmlUtils.parseByXpath(obj, xPath, XPathConstants.NODE); } /** * 通过XPath表达式获取某个xml节点的字符串值。 * * @param obj * 要被解析的對象。 * @param xPath * XPath表达式。 * @return 返回获取到的节点的字符串值。 * * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ public static String parseForString(final Object obj, final String xPath) throws NullPointerException, RuntimeException, XPathExpressionException { return (String) XmlUtils .parseByXpath(obj, xPath, XPathConstants.STRING); } /** * 通过XPath表达式获取某个xml节点的布尔值。 * * @param obj * 要被解析的對象。 * @param xPath * XPath表达式。 * @return 返回获取到的节点的布尔值。 * * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ public static Boolean parseForBoolean(final Object obj, final String xPath) throws NullPointerException, RuntimeException, XPathExpressionException { return (Boolean) XmlUtils.parseByXpath(obj, xPath, XPathConstants.BOOLEAN); } /** * 通过XPath表达式获取Node列表。 * * @param obj * 要被解析的對象。 * @param xPath * XPath表达式。 * @return 返回获取到的Node列表。 * * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ public static List parseForNodeList(final Object obj, final String xPath) throws NullPointerException, RuntimeException, XPathExpressionException { List lists = new ArrayList(); NodeList nList = (NodeList) XmlUtils.parseByXpath(obj, xPath, XPathConstants.NODESET); if (nList != null) { for (int i = 0; i < nList.getLength(); i++) { lists.add(nList.item(i)); } } return lists; } /** * 获取节点的制定属性。 * * @param node * 节点。 * @param attrName * 属性名。 * @return 返回获取到的属性值。如果找不到相关的 * */ public static String getAttribute(final Object node, final String attrName) { String result = ""; if ((node != null) && (node instanceof Node)) { if (((Node) node).getNodeType() == Node.ELEMENT_NODE) { result = ((Element) node).getAttribute(attrName); } else { // 遍历整个xml某节点指定的属性 NamedNodeMap attrs = ((Node) node).getAttributes(); if ((attrs.getLength() > 0) && (attrs != null)) { Node attr = attrs.getNamedItem(attrName); result = attr.getNodeValue(); } } } return result; } /** * 使用新节点替换原来的旧节点。 * * @param oldNode * 要被替换的旧节点。 * @param newNode * * 替换后的新节点。 * @exception DOMException * 如果此节点为不允许 * newNode节点类型的子节点的类型;或者如果要放入的节点为此节点的一个祖先或此节点本身;或者如果此节点为 * Document 类型且替换操作的结果将第二个 DocumentType 或 Element 添加到 * Document 上。 WRONG_DOCUMENT_ERR: 如果 newChild * 是从不同的文档创建的,不是从创建此节点的文档创建的,则引发此异常。 * NO_MODIFICATION_ALLOWED_ERR: 如果此节点或新节点的父节点为只读的,则引发此异常。 * NOT_FOUND_ERR: 如果 oldChild 不是此节点的子节点,则引发此异常。 * NOT_SUPPORTED_ERR: 如果此节点为 Document 类型,则如果 DOM 实现不支持替换 * DocumentType 子节点或 Element 子节点,则可能引发此异常。 */ public static void replaceNode(Node oldNode, Node newNode) { if ((oldNode != null) && (newNode != null)) { oldNode.getParentNode().replaceChild(newNode, oldNode); } } /** * 将Document输出到指定的文件中。 * * @param fileName * 文件名。 * @param node * 要保存的对象。 * @param encoding * 保存的编码。 * @throws FileNotFoundException * 指定的文件名不存在时,抛出此异常。 * @throws TransformerException * 如果转换过程中发生不可恢复的错误时,抛出此异常。 */ public static void saveXml(final String fileName, final Node node, String encoding) throws FileNotFoundException, TransformerException { XmlUtils.writeXml(new FileOutputStream(fileName), node, encoding); } /** * 将Document输出成字符串的形式。 * * @param node * Node对象。 * @param encoding * 字符串的编码。 * @return 返回输出成的字符串。 * @throws TransformerException * 如果转换过程中发生不可恢复的错误时,抛出此异常。 * @throws UnsupportedEncodingException * 指定的字符串编码不支持时,抛出此异常。 */ public static String nodeToString(Node node, String encoding) throws TransformerException, UnsupportedEncodingException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XmlUtils.writeXml(outputStream, node, encoding); return outputStream.toString(encoding); } /** * 将指定的Node写到指定的OutputStream流中。 * * @param encoding * 编码。 * @param os * OutputStream流。 * @param node * Node节点。 * @throws TransformerException * 如果转换过程中发生不可恢复的错误时,抛出此异常。 */ private static void writeXml(OutputStream os, Node node, String encoding) throws TransformerException { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, encoding); DOMSource source = new DOMSource(); source.setNode(node); StreamResult result = new StreamResult(); result.setOutputStream(os); transformer.transform(source, result); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值