How Java uses XPath expressions to query XML nodes and return information such as node collections and attributes

In Java, you can use XPath expressions to query XML nodes and return information such as node collections and attributes. Java provides the javax. xml. xpath package to support XPath queries. The following is an example code for querying and returning a node set using XPath: Firstly, the following Maven dependencies need to be added: <dependency> <groupId>javax.xml</groupId> <artifactId>javax.xml-api</artifactId> <version>1.0.1</version> </dependency> Next, let's assume the following XML example: <root> <element attribute="attributeValue1">value1</element> <element attribute="attributeValue2">value2</element> <element attribute="attributeValue3">value3</element> </root> Then, you can use the following Java code to query and return the node set using XPath: import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class XPathExample { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("path/to/xml/file.xml"); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); //Query Node Collection XPathExpression expr = xpath.compile("//element"); NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); //Traverse the node set, merge and print node and attribute values for (int i = 0; i < nodeList.getLength(); i++) { String value = nodeList.item(i).getTextContent(); String attribute = nodeList.item(i).getAttributes().getNamedItem("attribute").getNodeValue(); System.out.println("Value: " + value + ", Attribute: " + attribute); } } } In the above code, the XPath expression "//element" is used to query the collection of nodes named "element" in the XML document. In the code, we call the evaluate method of XPath and specify the XPathConstants. NODESET parameter to obtain the node set. Then, traverse the node set and use the getAttributes and getNamedItem methods to obtain the attribute values and node values of the node. It should be noted that the 'path/to/xml/file. xml' in the code should be replaced with the actual XML file path. I hope it can help you!