2011-05-08 54 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