|
|奔日网技术学堂欢迎您
tech.8BR.NET|
Element e; Attr att;// 属性对象 NamedNodeMap nnm;// 属性对象集合 String attrname; String attrval; for (int i = 0; i < nl.getLength(); i++) { e = (Element) nl.item(i); System.out.println(e.getTagName() + ":" + e.getFirstChild().getNodeValue()); nnm = e.getAttributes(); if (nnm != null) { for (int j = 0; j < nnm.getLength(); j++) { att = (Attr) nnm.item(j); attrname = att.getName(); attrval = att.getValue(); System.out.println("属性是:" + attrname + "=" + attrval); } } } } /* * 此为添加方法 */ public static void addElement(Document dc) { Element estu = dc.createElement("student"); Element ename = dc.createElement("name"); Element esex = dc.createElement("sex"); Element eage = dc.createElement("age"); Element escore = dc.createElement("score"); Text tname = dc.createTextNode("张三"); Text tsex = dc.createTextNode("男"); Text tage = dc.createTextNode("18"); Text tscore = dc.createTextNode("80"); estu.appendChild(ename).appendChild(tname); estu.appendChild(esex).appendChild(tsex); estu.appendChild(eage).appendChild(tage); estu.appendChild(escore).appendChild(tscore); dc.getDocumentElement().appendChild(estu); } /* * 此为修改方法 */ public static void updateElement(Document dc, String stname, String stscore) { NodeList nl = dc.getElementsByTagName("name"); Element e; for (int i = 0; i < nl.getLength(); i++) { e = (Element) nl.item(i); if (e.getFirstChild().getNodeValue().equals(stname)) { Node n = e.getParentNode(); NodeList nd = n.getChildNodes(); for (int j = 0; j < nd.getLength(); j++) { Node node = nd.item(j); if (node.getNodeName().equals("score")) { node.getFirstChild().setNodeValue(stscore);
} } } } } /* * 此方法为删除方法 */ public static void delElement(Document dc, String idValue) { NodeList nl=dc.getElementsByTagName("student"); Element e; NamedNodeMap nnm;//属性集合 Attr att; for(int i=0;i<nl.getLength();i++){ e=(Element)nl.item(i); nnm=e.getAttributes(); if(nnm!=null){ for(int j=0;j<nnm.getLength();j++){ att=(Attr)nnm.item(j); if((att.getName().equals("id"))&&(att.getValue().equals(idValue))){ (e.getParentNode()).removeChild(e); } } } } } /* * 此方法把在程序中所做的操作保存于xml文档中 */ public static void saveXml(Document dom) { TransformerFactory tff = TransformerFactory.newInstance(); try { Transformer tf = tff.newTransformer(); tf.setOutputProperty("encoding", "utf-8"); tf.transform(new DOMSource(dom), new StreamResult( "E:\\xml\\xmlExample\\student.xml")); } catch (Exception e) { e.printStackTrace(); } } /** * main方法 */ public static void main(String[] args) { Document dc = getInstance("E:\\xml\\xmlExample\\student.xml"); // printAll(dc); // addElement(dc); //updateElement(dc, "aa", "68"); delElement(dc,"100"); saveXml(dc); printAttr(dc); } } 本文共2页 当前在第2页 [首页] [上一页] [下一页] [末页]
|
发表对
对XML文档进行添、删、改、查的程序
的评论 请文明聊天 |
|点此可收藏|或发表对本篇的评论
|