DOM解析XML 作者: jiajunde 发表日期: 2007-05-12 14:55 文章属性: 原创 复制链接 |
/** * 写这个主要是为了自己练习 **/ 首先我们知道xml是被树状描述 再此,来做一个列子 package org.jiajd.xmldemo; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Attr; import org.w3c.NodeList; import org.w3c.NamedNodeMap; import org.w3c.Node; import org.w3c.SAXException; public class XmlTestDemo{ //获取这颗树 private static Document getDocument(String xmlPath){ Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory().newInstance(); //这里会报异常 try{ DocumentBuilder db = dbf.newDocumentBuilder(); //以上用静态工厂来处理 doc = db.parse(xmlPath); }catch(SAXException e){ //出错打出堆栈信息 e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }catch(ParserConfigurationException e){ e.printStackTrace(); } return doc; } /** 这个静态方法须要参数为这个树 * 打出里节点的值 **/ private static void showTree(Document doc){ //获取一个包含多元素的集合 Node node = null; NodeList nodelist = doc.getElementsByTagName("这里是根节点"); //用循环对这个元素进行操作 for(int i=0;i<nodelist.getLength();i++){ //获取当前集合中的元素 node = nodelist.item(i); //先看当前元素的属性 NamedNodeMap nnm = node.getAttributes(); //如果当前元素有属性那么nnm则有值 for(int j=0;j<nnm.getLength;j++){ Attr attr = (Attr)nnm.item(j); System.out.println("名:"+attr.getName()+" = "+attr.getValue()); } //再看看子元素 NodeList al = node.getChildNodes(); for(int j=0;al.getLength();j++){ Node no = al.item(j); if(no.hasChildNodes()){ //如果没有子元素则不打印 System.out.println("/t子元素:"+no.getNodeName()+" = "+no.getFirstChild().getNodeValue()); //no.getFirstChild().getNodeValue();是当前元素的子本属性的值 } } } } //这是一个main()方法 private static void main(String [] args){ XmlTestDemo.showTree(XmlTestDemo.getDocument("传入xml文档的路径和全名")); } } //ok了 总结: 无论什么语言.原来是相通的. 虽然现在的技术是五花八门的.其实基础是一样的.就像c.后来带类库的c.. |
DOM解析XML
最新推荐文章于 2024-04-08 14:20:35 发布