写了Android中解析xml文件的接口。注意传入的xml路径类型是
否则会报异常的。String path = "file:///data/data/com.example.androiddemo/network.xml";
这个在Android模拟器上测试过,可以正常使用。
package com.example.androiddemo;import java.util.HashMap;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Result;import javax.xml.transform.Source;import javax.xml.transform.Transformer;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 org.w3c.dom.NodeList;import android.util.Log;public class parseXML {private static final String TAG = "parseXMl";private static DocumentBuilderFactory factory = null;private static DocumentBuilder builder = null;private static Document doc = null;public static Document getDocument(String xml){if(doc != null) return doc;try {factory = DocumentBuilderFactory.newInstance();builder = factory.newDocumentBuilder();doc = builder.parse(xml);}catch(Exception ex){ex.printStackTrace();}return doc;}public static HashMap<String, String> loadXML(String xml){doc = getDocument(xml);HashMap<String, String> map = new HashMap<String, String>();try {Element root = doc.getDocumentElement(); //获得root元素NodeList nl = root.getElementsByTagName("item"); //获得item标签的结点集合for(int i=0; i<nl.getLength(); i++){Element element = (Element)nl.item(i);String name = element.getAttribute("name");String value = element.getFirstChild().getNodeValue();Log.d(TAG, "name : "+name+", value : "+value);map.put(name, value);element.getFirstChild().setNodeValue("####"); //修改节点值}}catch (Exception ex){ex.printStackTrace();}return map;}/** * 将上面修改了结点的Document对象写入到xml文件outXml中 * * @param doc * @param outXml */public static void updateXMl(Document doc, String outXml) {Source source = new DOMSource(doc);TransformerFactory factory = TransformerFactory.newInstance();Transformer transformer = null;try{transformer = factory.newTransformer();Result result = new StreamResult(outXml);transformer.transform(source, result);}catch(Exception ex){ex.printStackTrace();}}}
Android中解析xml文件的接口
最新推荐文章于 2024-07-08 03:26:44 发布