2014-02-11 14 views
1

我試圖在DOM解析器的幫助下解析Lingvo xml字典。DOM解析器沒有看到子節點

問題: DOM解析器不見card節點的子節點(見下面的代碼)。

問題?:如何從card節點拉wordtranslation節點

我的代碼:

import entity.Item; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
import org.xml.sax.SAXException; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

public class DOMParser { 

    public void parseXMLFile(String xmlFilePath) throws IOException, SAXException { 
     Document document = builder.parse(ClassLoader.getSystemResourceAsStream(xmlFilePath)); 
     List<Item> itemList = new ArrayList<Item>(); 
     NodeList nodeList = document.getDocumentElement().getChildNodes(); 
     //iterates through cards 
     for (int i = 0; i < nodeList.getLength(); i++) { 
      Node node = nodeList.item(i); 
      System.out.println(node.getNodeName()); 
      if (node instanceof Element) { 
       if ("card".equals(node.getNodeName())) { 
        // HERE node hasn't got anything!!! I mean attributes, childs etc. 
       } 
      } 
     } 
    } 
} 

我的XML:

<?xml version="1.0" encoding="UTF-16"?> 
<dictionary formatVersion="5" title="User ;vocabulary_user1" sourceLanguageId="1058" destinationLanguageId="1033" nextWordId="611" targetNamespace="http://www.abbyy.com/TutorDictionary"> 
    <statistics readyMeaningsQuantity="90" activeMeaningsQuantity="148" learnedMeaningsQuantity="374" /> 
    <card> 
     <word>загальна цікавість</word> 
     <meanings> 
      <meaning> 
       <statistics status="4" answered="122914" /> 
       <translations> 
        <word>genaral wondering</word> 
       </translations> 
      </meaning> 
     </meanings> 
    </card> 
</dictionary> 
+1

檢查這個解析XML的基礎http://www.mkyong.com/java/how-to-read-xml- file-in-java-dom-parser/....如何訪問節點及其值 – Naren

+0

@Naren我已經閱讀過這個tutoril http://www.javacodegeeks.com/2013/05/parsing-xml-使用-DOM-SAX-和STAX解析器功能於java.html –

回答

2

您可以使用遞歸方法來讀取所有內容,而不會陷入嵌套for循環的混亂狀態。

爲XML:

public static void main(String[] args) throws ParserConfigurationException, 
      SAXException, IOException { 
     InputStream path = new FileInputStream("dom.xml"); 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document document = builder.parse(path); 
     traverse(document.getDocumentElement()); 

    } 

    public static void traverse(Node node) { 
     NodeList list = node.getChildNodes(); 
     for (int i = 0; i < list.getLength(); i++) { 
      Node currentNode = list.item(i); 
      traverse(currentNode); 

     } 

     if (node.getNodeName().equals("word")) { 
      System.out.println("This -> " + node.getTextContent()); 
     } 

    } 

給人,

This -> загальна цікавість 
This -> genaral wondering