-- 作者:linlingyue
-- 发布时间:8/15/2007 5:56:00 PM
-- 关于DOM解析XML问题
我从网上找了一个DOM解析XML的程序,程序基本理解了,就是没有测试成功,我不知道XML应该放在什么地方才可以读取,希望大家给指点一下,我把代码拿出来共享一下: package com.lly.test; import javax.xml.parsers.*; import java.io.*; import org.w3c.dom.*; import org.xml.sax.*; /* * XML范例 * <?xml version="1.0" encoding="gb2312"?> <books> <book email="zhoujunhui"> <name>rjzjh</name> <price>jjjjjj</price> </book> </books> */ public class DomParseXml { public DomParseXml() { DocumentBuilderFactory objDBF = DocumentBuilderFactory.newInstance() ; try { DocumentBuilder objDB = objDBF.newDocumentBuilder(); InputStream objIS = new FileInputStream( "bin/libary.xml" ); Document objD = objDB.parse( objIS ); Element objE = objD.getDocumentElement(); NodeList objNL = objE.getChildNodes() ; // 节点的集合 if ( objNL != null ) { for ( int i =0 ; i < objNL.getLength() ; i ++ ) { Node objN = objNL.item( i ); if ( objN.getNodeType() == Node.ELEMENT_NODE ) { String strEmail = objN.getAttributes().getNamedItem( "email" ).getNodeValue(); System.out.println( "email--->" + strEmail ); for ( Node objSN = objN.getFirstChild() ; objSN != null ; objSN = objSN.getNextSibling() ) { if ( objSN.getNodeType() == Node.ELEMENT_NODE ) { if ( objSN.getNodeName().equals( "name" )) { String strName = objSN.getNodeValue() ; String strNName = objSN.getFirstChild().getNodeValue(); System.out.println( "strName--->" + strName ); System.out.println( "strNName--->" + strNName ); } if (objSN.getNodeName().equals( "price" )) { String strPrice = objSN.getNodeValue() ; System.out.println( "strPrice-->" + strPrice ); } } } } } } } catch ( ParserConfigurationException e ) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } catch(SAXException e) { e.printStackTrace(); } } public static void main(String args[]) { new DomParseXml(); } }
|