我有一个XML结构与此类似:
我有一个具有subcategory
list(List
)的Category类.我正在尝试使用XPath解析此XML文件,但我无法获取类别的子类别.
我怎么能用XPath做到这一点?有一个更好的方法吗?
此链接包含您需要的一切.简而言之:
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()); } }