2012-03-18 106 views
3

我有這樣的XML結構,當我使用NodeList nList = doc.getElementsByTagName(「stock」);它返回我3股,2個主要股票標籤和一個在underocks下。我想只得到兩個在上面的股票,並且忽略所有在上面的代碼下的股票。Java XML解析/查詢

是否有可能在Java中使用C#中的LINQ查詢之類的東西,只返回名稱等於「Sony」的元素。

謝謝!

<city> 
    <stock> 
    <name>Sony</name> 
    </stock> 
    <stock> 
    <name>Panasonic</name> 
    <substocks> 
      <stock> 
      <name>Panasonic Shop 2</name> 
      </stock> 
    </substocks> 
    </stock> 
</city> 

回答

3

我建議你使用XPathjavax.xml.xpath包:

final InputStream is = new FileInputStream('your.xml'); 

final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
final DocumentBuilder builder = factory.newDocumentBuilder(); 
final Document doc = builder.parse(is); 
final XPathFactory xPathfactory = XPathFactory.newInstance(); 
final XPath xpath = xPathfactory.newXPath(); 
final XPathExpression expr = xpath.compile("/city/stock/name[text()='Sony']"); 

然後:

final NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); 
+0

他只想元素,其中name =索尼,這樣的表達應該是'/城市/股[名稱= '索尼'] 「對嗎? – ebaxt 2012-03-18 14:18:05

+0

@ebaxt謝謝,我忘了。 – 2012-03-18 14:19:40

1

看看XPath及其java執行JXPath。其他可能的方法是使用JAXB解析XML,使用LambdaJ解析操作對象列表。

1

還有dom4j庫,它具有使用XPath強大的導航:

import org.dom4j.Document; 
import org.dom4j.io.SAXReader; 

SAXReader reader = new SAXReader(); 
Document document = reader.read("test.xml"); 
List list = document.selectNodes("/city/stock/name[text()='Sony']"); 
for (Iterator iter = list.iterator(); iter.hasNext();) { 
    // TODO: place you logic here 
} 

更多的例子是here

0

嘗試jcabi-xml(見本blog post)用一行代碼:

Collection<XML> found = new XMLDocument("your document here").nodes(
    "/city/stock/name[text()='Sony']" 
);