2011-05-08 57 views
0

我正在嘗試使用java讀取XML file。我可以成功讀取文件,但問題是,我不知道如何讀取列標籤內的值。使用java讀取XML的內容

由於列標籤不是唯一的,我不知道如何閱讀它們。有人能幫我嗎。

在此先感謝。

import java.net.URL; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 

public class XMLReader { 

public static void main(String argv[]) { 

    try { 
     //new code 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     Document doc = db.parse(new URL("http://www.cse.lk/listedcompanies/overview.htm?d-16544-e=3&6578706f7274=1").openStream()); 

     doc.getDocumentElement().normalize(); 
     System.out.println("Root element " + doc.getDocumentElement().getNodeName()); 
     NodeList nodeLst = doc.getElementsByTagName("row"); 
     System.out.println("Information of all Stocks"); 

     for (int s = 0; s < nodeLst.getLength(); s++) { 

     Node fstNode = nodeLst.item(s); 

     if (fstNode.getNodeType() == Node.ELEMENT_NODE) { 

      Element fstElmnt = (Element) fstNode; 
      //NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("column"); 
      //Element fstNmElmnt = (Element) fstNmElmntLst.item(0); 
      //NodeList fstNm = fstNmElmnt.getChildNodes(); 
      //System.out.println("First Tag : " + ((Node) fstNm.item(0)).getNodeValue()); 
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("column"); 
     // Element lstNmElmnt = (Element) lstNmElmntLst.item(0); 

      for (int columnIndex = 0; columnIndex < lstNmElmntLst.getLength(); columnIndex++) { 
       Element lstNmElmnt = (Element) lstNmElmntLst.item(columnIndex); 
       NodeList lstNm = lstNmElmnt.getChildNodes(); 
       System.out.println("Last Tag : " + ((Node) lstNm.item(0)).getNodeValue()); 
       } 

     } 

     } 
     } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 

回答

1

現在坐上NPE:

<column/> 

和你得到的元素0前,應查看列表規模:

NodeList lstNm = lstNmElmnt.getChildNodes(); 
if (lstNm.getLength() > 0) { 
    System.out.println("Last Tag : " + ((Node)lstNm.item(0)).getNodeValue()); 
} else { 
    System.out.println("No content"); 
} 

而當你正在處理中的節點文本內容,看看the answer to this SO question。文本節點irriting爲:

<foo> 
    a 
    b 
    c 
</foo> 

可以或者富的不止一個孩子節點,getTextContent()可以緩解疼痛了一下。

2

此代碼:

NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("column"); 

返回柱節點的列表,爲什麼不直接使用一個for循環在他們遍歷所有,而不是僅僅閱讀的第一個?

for (int columnIndex = 0; columnIndex < fstNmElmntLst.getLength(); columnIndex++) { 
Element fstNmElmnt = (Element) fstNmElmntLst.item(columnIndex); 
... 
} 
+0

我按照您的建議更改了代碼,但它現在打印出空白點。 System.out.prinln行打印空點。請檢查上面的更新代碼。 please – 2011-05-08 18:34:23

+0

查看extraneon的其他回覆! – 2011-05-08 22:50:44