Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 =
- "<library>" +
- "<section name='Fiction'>" +
- "<book id='b1' category='fantasy' rating='4.8'>" +
- "<title>Harry Potter and the Philosopher's Stone</title>" +
- "<author nationality='British'>J.K. Rowling</author>" +
- "<price currency='USD'>29.99</price>" +
- "</book>" +
- "<book id='b2' category='fantasy' rating='4.2'>" +
- "<title>The Hobbit</title>" +
- "<author nationality='British'>J.R.R. Tolkien</author>" +
- "<price currency='USD'>25.00</price>" +
- "</book>" +
- "</section>" +
- "<section name='Nonfiction'>" +
- "<book id='b3' category='history' rating='4.7'>" +
- "<title>Sapiens</title>" +
- "<author nationality='Israeli'>Yuval Noah Harari</author>" +
- "<price currency='USD'>35.00</price>" +
- "</book>" +
- "<book id='b4' category='science' rating='4.5'>" +
- "<title>Brief Answers to the Big Questions</title>" +
- "<author nationality='British'>Stephen Hawking</author>" +
- "<price currency='USD'>28.00</price>" +
- "</book>" +
- "</section>" +
- "</library>";
- // --- 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();
Advertisement
Add Comment
Please, Sign In to add comment