javax.xml.xpath


1. Extracting Data from an XML File

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

public class XpathDemo {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new File("sample.xml"));
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        NodeList nodes = (NodeList) xpath.evaluate("/root/item", doc, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            System.out.println(node.getNodeValue());
        }
    }
}

2. Searching for Specific Nodes

3. Selecting Nodes Based on Attribute Values

4. Using Predicates in XPath Expressions

5. Combining Predicates in XPath Expressions

6. Extracting Multiple Attributes from a Node

7. Extracting Text Content from a Node

8. Using Functions in XPath Expressions

9. Using XPath in JAXP

10. Using XPath to Transform XML

11. Using XPath to Validate XML

12. Using XPath to Create XML

13. Using XPath to Update XML

14. Using XPath to Delete XML

15. Using XPath to Copy XML

16. Using XPath to Sort XML