import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
// --- 1. Sample XML ---
xml =
"" +
"" +
"" +
"Harry Potter and the Philosopher's Stone" +
"J.K. Rowling" +
"29.99" +
"" +
"" +
"The Hobbit" +
"J.R.R. Tolkien" +
"25.00" +
"" +
"" +
"" +
"" +
"Sapiens" +
"Yuval Noah Harari" +
"35.00" +
"" +
"" +
"Brief Answers to the Big Questions" +
"Stephen Hawking" +
"28.00" +
"" +
"" +
"";
// --- 2. Parse XML ---
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
builder = factory.newDocumentBuilder();
doc = builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
// --- 3. Setup XPath ---
xpath = XPathFactory.newInstance().newXPath();
results = "";
// --- 4. Define helper function (as global) ---
void queryAndAppend(String label, String pattern, String type) throws Exception {
expr = xpath.compile(pattern);
results += "[" + label + "] " + pattern + "\n";
if (type.equals("nodes")) {
nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (nodes.getLength() == 0) {
results += "(no match)\n\n";
return;
}
for (i = 0; i < nodes.getLength(); i++) {
val = nodes.item(i).getNodeValue();
if (val == null) val = nodes.item(i).getTextContent();
results += "- " + val + "\n";
}
results += "\n";
} else if (type.equals("value")) {
val = xpath.evaluate(pattern, doc);
results += "→ " + val + "\n\n";
}
}
// --- 5. Run multiple queries ---
queryAndAppend("A", "//book/title/text()", "nodes");
queryAndAppend("B", "//author[@nationality='British']/text()", "nodes");
queryAndAppend("C", "//book[number(price) > 28]/title/text()", "nodes");
queryAndAppend("D", "//book[number(@rating) >= 4.5]/title/text()", "nodes");
queryAndAppend("E", "count(//book)", "value");
queryAndAppend("F", "//section/@name", "nodes");
// --- 6. Return the full report ---
tasker.log("XPath Results:\n" + results);
return results.trim();