Android中XML的基本操作(增、删、改、查)
程序员文章站
2023-08-21 22:57:08
android中xml的一些操作
解析类:
// 构造方法
public xmlparser() {
}
/**...
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的权限!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
上一篇: 伤肾的食物都有哪些