日期:2014-05-20 浏览次数:20790 次
import javax.xml.parsers.*; import org.xml.sax.*; import java.io.*; import org.w3c.dom.*; public class code10_1{ static Document document; public static void main(String[] args){ if(args.length!=1){ System.out.println("加载xml file"); return; } DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); try{ DocumentBuilder db=dbf.newDocumentBuilder(); //读入XML文档 document=db.parse(new File(args[0])); //遍历XML文档 walkNode(document.getDocumentElement()); }catch(SAXException se){ //解析过程错误 Exception e=se; if(se.getException()!=null) e=se.getException(); e.printStackTrace(); }catch(ParserConfigurationException pe){ //解析器设定错误 pe.printStackTrace(); }catch(IOException ie){ //文件处理错误 ie.printStackTrace(); } } private static void walkNode(Node anode){ NodeList child=anode.getChildNodes(); printNode(anode); for(int i=0;i<child.getLength();i++){ Node node=child.item(i); if(node.hasChildNodes()) walkNode(node); else printNode(node); } } private static void printNode(Node anode){ System.out.println(anode.getNodeName()+","+anode.getNodeValue()); } }
import javax.xml.parsers.*; import org.xml.sax.*; import java.io.*; import org.w3c.dom.*; public class code10_1{ static Document document; public static void main(String[] args){ if(args.length!=1){ System.out.println("????xml file"); return; } DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); try{ DocumentBuilder db=dbf.newDocumentBuilder(); //????XML??? document=db.parse(new File(args[0])); //????XML??? walkNode(document.getDocumentElement()); }catch(SAXException se){ //?????????? Exception e=se; if(se.getException()!=null) e=se.getException(); e.printStackTrace(); }catch(ParserConfigurationException pe){ //???????趨???? pe.printStackTrace(); }catch(IOException ie){ //?????????? ie.printStackTrace(); } } private static void walkNode(Node anode){ NodeList child=anode.getChildNodes(); printNode(anode); for(int i=0;i<child.getLength();i++){ Node node=child.item(i); if(node.hasChildNodes()) walkNode(node); else printNode(node); } } private static void printNode(Node anode){ System.out.println(anode.getNodeName()+","+anode.getNodeValue()); } }