2013-01-10 151 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