Skip to content

Instantly share code, notes, and snippets.

@vernetto
Created June 23, 2024 06:09
Show Gist options
  • Save vernetto/c99181a5f053dc3b8a93111cd3e03d64 to your computer and use it in GitHub Desktop.
Save vernetto/c99181a5f053dc3b8a93111cd3e03d64 to your computer and use it in GitHub Desktop.
xpath
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class XPathQueryExecutor {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java XPathQueryExecutor <XML file> <XPath expression>");
return;
}
String xmlFilePath = args[0];
String xpathExpression = args[1];
try {
// Load XML file into a Document
File xmlFile = new File(xmlFilePath);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
// Create an XPath instance
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
// Compile and evaluate the XPath expression
XPathExpression expression = xPath.compile(xpathExpression);
NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
// Print the results
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment