簡體   English   中英

使用Java讀取XML的內容

[英]Reading contents of the XML using java

我正在嘗試使用Java讀取XML文件 我可以成功讀取文件,但是問題是,我不知道如何讀取column標記內的值。

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

提前致謝。

 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();
  }
 }
}

此代碼:

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

返回一個列節點列表,為什么不只使用for循環遍歷它們,而不是只讀取第一個?

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

現在,您將獲得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");
 }

在處理節點中的文本內容時,請查看此SO問題的答案 文本節點令人討厭:

<foo>
   a
   b
   c
 </foo>

可以是foo,也可以是不止一個子節點,並且getTextContent()可以減輕痛苦。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM