2013-01-10 34 views
2

我一直在尋找JAVA中的XML讀取示例,並且我總是發現一個典型的模式根 - > 3等於兒子 - > 3個相等的孫子。從XML直接獲取孫子元素

但有時你只需要得到一對不存儲爲書籍庫{書名,作者,頁數}的元素。我的XML看起來像:

<?xml version="1.0" encoding="UTF-8" ?> 
<A> 
    <Crap1> 
     <CrapSon>1</CrapSon> 
    </Crap1> 
    <B> 
     <Crap2>Store</Crap2> 
     <C> 
      <Type>N</Type> 
      <D> 
       <InterestingData1>Data</InterestingData1> 
      </D> 
      <InterestingData2>More Data</InterestingData2> 
     </C> 
    </B> 
</A> 

當然,我可以迭代它,最後得到我想要的數據元素。但是有沒有什麼快速的方式來訪問你想要的元素,而不是迭代樹,只是通過名稱並讓它搜索它?

+1

[XPATH](http://onjava.com/pub/a/onjava/2005/01/12/xpath.html) – gks

回答

0

如果你不想DOM,我想你應該使用SAX解析器與處理程序處理InterestingData1InterestingData2

1

你可以嘗試像以下:

import java.io.IOException; 
import java.io.StringReader; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 

import org.w3c.dom.Document; 
import org.w3c.dom.NodeList; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 

class Test {  

    public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException{ 
     String xmlString ="<A>" + 
       "<Crap1><CrapSon>1</CrapSon>" + 
       "</Crap1>" + 
       "<B>" + 
       "<Crap2>Store</Crap2><C><Type>N</Type><D><InterestingData1>Data</InterestingData1></D><InterestingData2>More Data</InterestingData2></C>" + 
       "</B>" + 
       "</A>"; 

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
     DocumentBuilder docBuilder = dbf.newDocumentBuilder(); 
     Document doc = docBuilder.parse(new InputSource(new StringReader(xmlString))); 

     NodeList nodelist = doc.getElementsByTagName("InterestingData2"); 
     NodeList nodelist2 = doc.getElementsByTagName("Type"); 

     String str = nodelist.item(0).getTextContent(); 
     String str2 = nodelist2.item(0).getTextContent(); 

     System.out.println("InterestingData2: "+str); 
     System.out.println("Type: " + str2); 
    } 
} 

輸出:

InterestingData2:更多數據

類型:N