import org.w3c.dom.*;
          import javax.xml.parsers.*;
          import java.io.*;
          public class Parse {
           //Document可以看作是XML在內存中的一個鏡像,那么一旦獲取這個Document 就意味著可以通過對
            //內存的操作來實現對XML的操作,首先第一步獲取XML相關的Document
             private Document doc=null;
           
            public void init(String xmlFile) throws Exception{
             //很明顯該類是一個單例,先獲取產生DocumentBuilder工廠
             //的工廠,在通過這個工廠產生一個DocumentBuilder,
             //DocumentBuilder就是用來產生Document的
             DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
             DocumentBuilder db=dbf.newDocumentBuilder(); 
             //這個Document就是一個XML文件在內存中的鏡像
             doc=db.parse(new File(xmlFile));
            }
            //該方法負責把XML文件的內容顯示出來
           
            public void viewXML(String xmlFile) throws Exception{
             this.init(xmlFile);
             //在xml文件里,只有一個根元素,先把根元素拿出來看看
             Element element=doc.getDocumentElement();
             System.out.println("根元素為:"+element.getTagName());
            
             NodeList nodeList=doc.getElementsByTagName("story");
             System.out.println("story節點鏈的長度:"+nodeList.getLength());
            
             Node fatherNode=nodeList.item(0);
             System.out.println("父節點為:"+fatherNode.getNodeName());
            
             //把父節點的屬性拿出來
             NamedNodeMap attributes=fatherNode.getAttributes();
            
          //   for(int i=0;i<attributes.getLength();i++){
          //    Node attribute=attributes.item(i);
          //    System.out.println("person的屬性名為:"+attribute.getNodeName()+" 相對應的屬性值為:"+attribute.getNodeValue());
          //   }

             NodeList childNodes = fatherNode.getChildNodes();
             System.out.println(childNodes.getLength());
             for(int j=0;j<2;j++){
              Node childNode=childNodes.item(j);
              //如果這個節點屬于Element ,再進行取值
              if(childNode instanceof Element){
               //System.out.println("子節點名為:"+childNode.getNodeName()+"相對應的值為"+childNode.getFirstChild().getNodeValue());
               System.out.println("子節點名為:"+childNode.getNodeName()+"相對應的值為"+childNode.getFirstChild().getNodeValue());
              }
             }
            
            }
           
            public static void main(String[] args)throws Exception{
             Parse parse=new Parse();

           //我的XML文件
             parse.viewXML("D:/Tomcat 5.5/webapps/ROOT/story/best_story.xml");
            }
          }

          posted on 2008-07-25 17:39 lzj520 閱讀(280) 評論(0)  編輯  收藏 所屬分類: 個人學習日記
          主站蜘蛛池模板: 巴东县| 依安县| 嘉兴市| 东海县| 滨州市| 中牟县| 富民县| 谷城县| 古蔺县| 合江县| 会同县| 武冈市| 瑞昌市| 德惠市| 象州县| 驻马店市| 汾阳市| 拉萨市| 嘉荫县| 红河县| 佛教| 卫辉市| 安顺市| 卢龙县| 无为县| 广丰县| 贵定县| 淳化县| 丰原市| 集安市| 三门县| 巢湖市| 德安县| 扎赉特旗| 彭泽县| 北安市| 崇礼县| 西充县| 平潭县| 沙河市| 南岸区|