Android中XML的一系列操作,增、删、改、查!!!

Android中XML的一些操作,直接看代码!!!

解析类:

// 构造方法
	public XMLParser() {

	}

	/**
	 * 从URL获取XML使HTTP请求
	 * 
	 * @param url
	 *            string
	 * */
	public String getXmlFromUrl(String url) {
		String xml = null;

		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			xml = EntityUtils.toString(httpEntity, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml;
	}

	/**
	 * 获取XML DOM元素
	 * 
	 * @param XML
	 *            string
	 * */
	public Document getDomElement(InputStream is) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			// InputSource is = new InputSource();
			// is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is);
		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}

		return doc;
	}

	public Document getDomDocumentUpdate(String xml) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is);
		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}

		return doc;
	}

	/**
	 * 获取节点值
	 * 
	 * @param elem
	 *            element
	 */
	public final String getElementValue(Node elem) {
		Node child;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (child = elem.getFirstChild(); child != null; child = child
						.getNextSibling()) {
					if (child.getNodeType() == Node.TEXT_NODE) {
						return child.getNodeValue();
					}
				}
			}
		}
		return "";
	}

	/**
	 * 获取节点值
	 * 
	 * @param Element
	 *            node
	 * @param key
	 *            string
	 * */
	public String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return this.getElementValue(n.item(0));
	}
	//XML文件有更新后,调用此方法
	public void output(Document node, String filename) {
		TransformerFactory transFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = transFactory.newTransformer();
			// 设置各种输出属性
			transformer.setOutputProperty("encoding", "UTF-8");
			transformer.setOutputProperty("indent", "yes");
			DOMSource source = new DOMSource(node);
			// 将待转换输出节点赋值给DOM源模型的持有者(holder)
			// /source.setNode(node);
			StreamResult result = new StreamResult();
			if (filename == null) {
				// 设置标准输出流为transformer的底层输出目标
				result.setOutputStream(System.out);
			} else {
				result.setOutputStream(new FileOutputStream(filename));
			}
			// 执行转换从源模型到控制台输出流
			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public String writeXml() {
		XmlSerializer xml = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			xml.setOutput(writer);
			xml.startDocument("UTF-8", true);
			xml.startTag("", "blog");

			xml.startTag("", "message");
			xml.attribute("", "name", "xia");
			xml.startTag("", "age");
			xml.text("22");
			xml.endTag("", "age");

			xml.startTag("", "hobby");
			xml.text("play");
			xml.endTag("", "hobby");

			xml.startTag("", "hight");
			xml.text("165");
			xml.endTag("", "hight");
			xml.endTag("", "message");

			xml.startTag("", "message");
			xml.attribute("", "name", "chen");
			xml.startTag("", "age");
			xml.text("21");
			xml.endTag("", "age");

			xml.startTag("", "hobby");
			xml.text("swin");
			xml.endTag("", "hobby");

			xml.startTag("", "hight");
			xml.text("170");
			xml.endTag("", "hight");
			xml.endTag("", "message");

			xml.endTag("", "blog");
			xml.endDocument();

		} catch (Exception e) {
			throw new RuntimeException(e);  
		}

		return  writer.toString();
	}

	

	public boolean Write(String Filepath, String txt) {
		FileOutputStream fos = null;
		if (Environment.getExternalStorageState() != null) {// 这个方法在试探终端是否有sdcard!
			File path = new File("sdcard/test");// 创建目录
			File f = new File(Filepath);// 创建文件
			if (!path.exists()) {// 目录不存在返回false
				path.mkdirs();// 创建一个目录
			}
			if (!f.exists()) {// 文件不存在返回false
				try {
					f.createNewFile();
					fos = new FileOutputStream(f);
					fos.write((txt).getBytes("UTF-8"));
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}// 创建一个文件
			}

		}
		return true;
	}

	private static XMLParser uniqueInstance = null;

	public static XMLParser getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new XMLParser();
		}
		return uniqueInstance;
	}
}


上面的这个类中用了单例!分别定义了XML的创建,获取XML的节点值,更新后执行的操作!

MainActivity:

public class MainActivity extends Activity {
	public static final String XMLPath = "sdcard/test/message.xml";
	private Button create = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		create = (Button) findViewById(R.id.create);
	}

	// 自动创建XML
	private void createXml() {
		// sdcard/test/message.xml
		XMLParser.getInstance().Write(XMLPath,
				XMLParser.getInstance().writeXml());
	}

	// 遍历节点,找到特定节点并进行更换!
	private void selectNode() {
		Document document = null;
		try {
			FileInputStream fin = new FileInputStream(XMLPath);
			document = XMLParser.getInstance().getDomElement(fin);
			Node root = document.getDocumentElement();
			if (root.hasChildNodes()) {
				NodeList ftpnodes = root.getChildNodes();
				Log.e("eee", root.getNodeName());// 根节点 blog

				for (int i = 0; i < ftpnodes.getLength(); i++) {
					NodeList ftplist = ftpnodes.item(i).getChildNodes();
					Node su = ftpnodes.item(i);
					Log.e("eee", su.getNodeName());// message
					Element e = (Element) ftpnodes.item(i);
					Log.e("eee", e.getAttribute("name"));// message= xia
					for (int k = 0; k < ftplist.getLength(); k++) {
						Node subnode = ftplist.item(k);
						Log.e("eee",
								" subnode.getNodeName()"
										+ subnode.getNodeName());
						Log.e("eee",
								"subnode.getNodeType()" + subnode.getNodeType());
						Log.e("eee", subnode.getFirstChild().getNodeValue());
						if (subnode.getNodeType() == Node.ELEMENT_NODE
								&& subnode.getNodeName().equals("hight")) {
							subnode.getFirstChild().setNodeValue("175");
							XMLParser.getInstance().output(document, XMLPath);
						}
					}
				}
			}

		} catch (Exception e) {

		}
	}

	// 添加一个新的根节点
	private void insertNode() {
		Document document = null;
		try {
			FileInputStream fin = new FileInputStream(XMLPath);
			document = XMLParser.getInstance().getDomElement(fin);
			// 插入根节点message
			/**
			 * <message name="wang"> <hight>180</hight> <age>22</age> </message>
			 * 
			 * */
			Element eltStu = document.createElement("message");
			Element eltName = document.createElement("hight");
			Element eltAge = document.createElement("age");
			Attr attr = document.createAttribute("name");
			attr.setValue("wang");
			Text txtName = document.createTextNode("180");
			Text txtAge = document.createTextNode("22");
			eltName.appendChild(txtName);
			eltAge.appendChild(txtAge);
			eltStu.appendChild(eltName);
			eltStu.appendChild(eltAge);
			eltStu.setAttributeNode(attr);
			Element eltRoot = document.getDocumentElement();
			eltRoot.appendChild(eltStu);
			XMLParser.getInstance().output(document, XMLPath);
		} catch (Exception e) {

		}
	}

	private void instertChildNode() {
		Document document = null;
		try {
			FileInputStream fin = new FileInputStream(XMLPath);
			document = XMLParser.getInstance().getDomElement(fin);
			// 在某个根节点下面添加节点
			/**
			 * <message name="wang"> <hight>180</hight> <age>22</age>
			 * <hobby>music</hobby>//这句是新添加的 </message>
			 * 
			 * */
			Node root = document.getDocumentElement();
			NodeList ftpnodes = root.getChildNodes();
			Log.e("eee", root.getNodeName());// 根节点 blog
			NodeList ftplist = ftpnodes.item(1).getChildNodes();
			Node su = ftpnodes.item(1);
			Log.e("eee", su.getNodeName());// message
			Element e = (Element) ftpnodes.item(5);// message= wang
			Log.e("eee", e.getAttribute("name"));
			if (e.getAttribute("name").equals("wang")) {
				Element elthoby = document.createElement("hobby");
				Text txthoby = document.createTextNode("music");
				elthoby.appendChild(txthoby);
				Node stNode = document.getElementsByTagName("message").item(2);
				stNode.appendChild(elthoby);
			}
			XMLParser.getInstance().output(document, XMLPath);
		} catch (Exception e) {
		}
	}

	private void removeNode() {
		Document document = null;
		try {
			FileInputStream fin = new FileInputStream(XMLPath);
			document = XMLParser.getInstance().getDomElement(fin);
			// 删除blog下的message的0个节点
			NodeList nl = document.getElementsByTagName("message");
			Node nodeDel = (Element) nl.item(0);
			nodeDel.getParentNode().removeChild(nodeDel);
			XMLParser.getInstance().output(document, XMLPath);
		} catch (Exception e) {
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
最后记得添加读写SDcard的权限!

 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值