当我使用NodeList时,我有这样的XML结构nList = doc.getElementsByTagName(" stock");它归还给我3个股票,2个主要股票标签和一个在亚组件下。我想只获得两个位于较高级别的股票,并忽略所有在子标签下的股票。
在Java中是否有可能在C#中创建LINQ查询之类的东西,比如只返回名称等于"索尼"的元素。
谢谢!
<city>
<stock>
<name>Sony</name>
</stock>
<stock>
<name>Panasonic</name>
<substocks>
<stock>
<name>Panasonic Shop 2</name>
</stock>
</substocks>
</stock>
</city>
答案 0 :(得分:3)
我建议您将XPath与javax.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);
答案 1 :(得分:1)
看看XPath及其java实现JXPath。其他可能的方法是使用LambdaJ使用JAXB和操作对象列表解析XML。
答案 2 :(得分: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
答案 3 :(得分:0)