使用Java中的XPath解析XML [英] Parsing XML with XPath in Java
本文介绍了使用Java中的XPath解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的XML结构与此类似:
I have a XML with a structure similar to this:
<category>
<subCategoryList>
<category>
</category>
<category>
<!--and so on -->
</category>
</subCategoryList>
</category>
我有一个具有子类别
list( List< Category>
)。我正在尝试使用XPath解析此XML文件,但我无法获取类别的子类别。
I have a Category class that has a subcategory
list (List<Category>
). I'm trying to parse this XML file with XPath, but I can't get the child categories of a category.
如何使用XPath执行此操作?有没有更好的方法呢?
How can I do this with XPath? Is there a better way to do this?
推荐答案
此链接包含您需要的一切。简而言之:
This link has everything you need. In shorts:
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("//person/*/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
这篇关于使用Java中的XPath解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文