简体   繁体   English

Java XML Parse / Query

[英]Java XML Parse/Query

I have such XML structure, when I use NodeList nList = doc.getElementsByTagName("stock"); 我有这样的XML结构,当我使用NodeList nList = doc.getElementsByTagName(“stock”); it return me 3 stocks, 2 main stock tags and one which is under substocks. 它归还给我3个股票,2个主要股票标签和一个在亚组件下。 I want to get only two stock which is on upper level and ignore all which is under substock tags. 我想只获得两个位于较高级别的股票并忽略所有在子标签下的股票。

Is it possible in Java to make something like LINQ query in C#, say return me elements only where name is equals to "Sony". 在Java中是否有可能在C#中创建类似LINQ查询的东西,比如只返回name,其中name等于“Sony”。

Thanks! 谢谢!

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

I recommend you to use XPath with javax.xml.xpath package: 我建议你使用带有javax.xml.xpath包的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']");

and then: 然后:

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

Take a look on XPath and its java implementation JXPath . 看看XPath及其java实现JXPath Other possible approach is parsing XML using JAXB and operating objects list using LambdaJ. 其他可能的方法是使用LambdaJ使用JAXB和操作对象列表解析XML。

There is also dom4j library which has powerful navigation with XPath: 还有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
}

More examples are here 这里有更多的例子

Try jcabi-xml (see this blog post ) with a one-liner: 尝试jcabi-xml (请参阅此博客文章 ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM