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 閱讀(283) 評論(0)  編輯  收藏 所屬分類: 個人學習日記
          主站蜘蛛池模板: 布尔津县| 河津市| 棋牌| 武胜县| 张掖市| 吉木萨尔县| 任丘市| 乐昌市| 新和县| 山丹县| 邯郸市| 扎鲁特旗| 新建县| 岳阳市| 醴陵市| 连江县| 东阳市| 克东县| 高青县| 江源县| 嘉黎县| 台山市| 丹东市| 夏河县| 安龙县| 日照市| 科尔| 常宁市| 丘北县| 调兵山市| 天峻县| 凭祥市| 大化| 阳高县| 邹平县| 岑巩县| 萨嘎县| 合水县| 文山县| 咸阳市| 蓬安县|