一个简单的JAVA XML解析器

类别:Java 点击:0 评论:0 推荐:
 <?xml version="1.0" encoding="SHIFT-JIS" ?> - <SFCPDOCSEARCH>   <ERRNO>0</ERRNO>   <TIME>1.17</TIME>   <HITDOCS>1</HITDOCS>   <OUTDOCS>1</OUTDOCS>   <BLOCK>1</BLOCK> - <REC>       <LID>2</LID>       <LCHT>50</LCHT>       <LPG>216</LPG>       <BOOKNAME>MELEC</BOOKNAME>       <STA>2</STA>  </REC>  </SFCPDOCSEARCH>上面是这个程序用到的XML,实际上这个方法的传入参数是个URL,这个URL在浏览器中取得的结果就是上面的XML。
  private void parseURL(String strURL) {
    try {
      String[] strLID = null;
      URL url = new URL(strURL);
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setValidating(false);
      DocumentBuilder doc_builder = dbf.newDocumentBuilder();
      Document doc = doc_builder.parse(new InputSource(new InputStreamReader(url.openStream(),"SHIFT-JIS")));
     
      //Get root node
      Element rootElement = doc.getDocumentElement();
      if (rootElement == null){
        return;
      }
     
      NodeList paramNodeLists = doc.getElementsByTagName("LID");
      int iNodeCount = paramNodeLists.getLength();
      strLID = new String[iNodeCount];
      for (int i = 0; i < iNodeCount; i++) {
        strLID[i] = paramNodeLists.item(i).getFirstChild().getNodeValue().trim();
        System.out.println(“[“ + strLID[i]  + “]“);
      }
     
      this.strLID = strLID;
    }
    catch (Exception e) {
      this.strLID = null;
      return;
    }
  }
运行结果为:
[2]

本文地址:http://com.8s8s.com/it/it11428.htm