Archives
Trending
Support
Login
clear text
XML
Django
JavaScript
MATLAB
C
C++
C#
Python
SQL
Shell
Bash
Markdown
YAML
JSON
HTML
CSS
PHP
Java
Ruby
Go
Rust
Swift
Kotlin
Arduino
TypeScript
Perl
Autohotkey
Lua
SQF
R
Scala
Haskell
Groovy
Dart
Clojure
VB.NET
Objective-C
PowerShell
Bash
CoffeeScript
Verilog
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();
Mark as private (unlisted)
for 30 minutes
for 6 hours
for 1 day
for 1 week
for 1 month
for 1 year
everlasting (like CCCP)