Tester XPath
Testa espressioni XPath contro XML e visualizza tutti i nodi corrispondenti
Input XML
Cos'è XPath?
XPath (XML Path Language) è un linguaggio di query per selezionare nodi da un documento XML. Definito dal W3C come parte dello standard XSLT, XPath tratta un documento XML come un albero di nodi e fornisce una sintassi basata su percorsi per navigare quell'albero. Un'espressione XPath come //book[@category="fiction"]/title seleziona ogni elemento title all'interno di un elemento book il cui attributo category è uguale a "fiction". XPath 1.0, la versione supportata da tutti i principali browser e dalla maggior parte delle librerie XML, è stata pubblicata come W3C Recommendation nel 1999 e rimane la versione più diffusa.
Le espressioni XPath restituiscono uno di quattro tipi di risultato: node set, stringhe, numeri o booleani. Un node set è il risultato più comune e contiene zero o più nodi XML (elementi, attributi, nodi di testo, commenti o istruzioni di elaborazione). I risultati stringa, numero e booleano provengono da funzioni XPath come count(), sum(), contains() e da confronti booleani. Questo sistema di tipi rende XPath adatto sia all'estrazione di dati che alla scrittura di logica condizionale nei fogli di stile XSLT e nelle asserzioni degli XML Schema.
Le espressioni della versione 1.0 funzionano ovunque: document.evaluate() in JavaScript, lxml e ElementTree in Python, javax.xml.xpath in Java, DOMXPath in PHP e strumenti da riga di comando come xmllint. Le versioni 2.0 e 3.1 aggiungono sistemi di tipi e funzioni più ricchi ma richiedono engine dedicati come Saxon. Usa la versione 1.0 per impostazione predefinita. Passa alla 2.0 o 3.1 solo quando hai bisogno di sequenze, espressioni regolari o funzioni di ordine superiore — e accetta la dipendenza da Saxon o BaseX.
Perché usare un Tester XPath online?
Scrivere espressioni corrette richiede di comprendere la struttura del documento e di testare con dati reali. Lo strumento ti offre un ambiente interattivo per iterare sulle espressioni senza dover configurare un progetto o scrivere codice boilerplate.
Casi d'uso del Tester XPath
Riferimento agli assi XPath
Un asse definisce la direzione di navigazione rispetto al nodo corrente (contesto). La sintassi completa è asse::node-test[predicato], anche se la maggior parte degli sviluppatori usa ogni giorno le forme abbreviate (//, @, ..). Questa tabella elenca tutti gli assi 1.0 con esempi pratici.
| Asse | Esempio | Descrizione |
|---|---|---|
| child | child::book | Direct children named "book" |
| descendant | descendant::title | All "title" elements at any depth |
| parent | parent::* | The parent of the current node |
| ancestor | ancestor::catalog | All ancestors named "catalog" |
| following-sibling | following-sibling::book | Siblings after the current node |
| preceding-sibling | preceding-sibling::book | Siblings before the current node |
| attribute | attribute::lang | The "lang" attribute of the node |
| self | self::book | The current node if it is "book" |
| descendant-or-self | //title | Shorthand: any "title" in the tree |
| ancestor-or-self | ancestor-or-self::* | Current node plus all ancestors |
Funzioni XPath 1.0
Il linguaggio definisce 27 funzioni integrate in quattro categorie: node set, stringa, numero e booleano. Queste sono le funzioni che userai più spesso quando scrivi query. Tutte sono supportate da questo tester e da ogni implementazione conforme.
| Funzione | Categoria | Descrizione |
|---|---|---|
| text() | Node test | Selects text content of a node |
| position() | Numeric | Returns 1-based position in node set |
| last() | Numeric | Returns size of current node set |
| count() | Numeric | Counts nodes: count(//book) |
| contains() | String | contains(@class, "active") — substring match |
| starts-with() | String | starts-with(title, "The") — prefix match |
| normalize-space() | String | Strips leading/trailing whitespace |
| string-length() | Numeric | Returns character count of a string |
| sum() | Numeric | sum(//price) — totals numeric values |
| not() | Boolean | not(@disabled) — negation |
| name() | String | Returns element or attribute name |
Esempi di codice
Questi esempi mostrano come valutare le espressioni a livello programmatico. Ogni frammento usa la stessa struttura catalog.xml in modo da poter confrontare le differenze di API tra i linguaggi.
const xml = `<catalog>
<book id="1"><title>1984</title><price>7.99</price></book>
<book id="2"><title>Dune</title><price>12.99</price></book>
</catalog>`
const parser = new DOMParser()
const doc = parser.parseFromString(xml, 'application/xml')
// Select all book titles
const result = doc.evaluate('//book/title', doc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null)
let node = result.iterateNext()
while (node) {
console.log(node.textContent) // → "1984", "Dune"
node = result.iterateNext()
}
// Get a numeric value
const sum = doc.evaluate('sum(//price)', doc, null, XPathResult.NUMBER_TYPE, null)
console.log(sum.numberValue) // → 20.98from lxml import etree
xml = """<catalog>
<book id="1"><title>1984</title><price>7.99</price></book>
<book id="2"><title>Dune</title><price>12.99</price></book>
</catalog>"""
tree = etree.fromstring(xml.encode())
# Select elements by attribute
books = tree.xpath('//book[@id="1"]/title/text()')
print(books) # → ['1984']
# Use predicates with position
first = tree.xpath('//book[1]/title/text()')
print(first) # → ['1984']
# Boolean check
has_cheap = tree.xpath('boolean(//price[. < 10])')
print(has_cheap) # → Trueimport javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;
import org.w3c.dom.*;
var factory = DocumentBuilderFactory.newInstance();
var builder = factory.newDocumentBuilder();
var doc = builder.parse(new java.io.File("catalog.xml"));
var xpath = XPathFactory.newInstance().newXPath();
// Select node set
NodeList titles = (NodeList) xpath.evaluate(
"//book/title", doc, XPathConstants.NODESET
);
for (int i = 0; i < titles.getLength(); i++) {
System.out.println(titles.item(i).getTextContent());
// → "1984", "Dune"
}
// Evaluate to number
double total = (double) xpath.evaluate(
"sum(//price)", doc, XPathConstants.NUMBER
);
System.out.println(total); // → 20.98# Select all book titles xmllint --xpath '//book/title/text()' catalog.xml # → 1984Dune # Select by attribute xmllint --xpath '//book[@id="2"]/title' catalog.xml # → <title>Dune</title> # Count nodes xmllint --xpath 'count(//book)' catalog.xml # → 2 # Using xmlstarlet for formatted output xmlstarlet sel -t -v '//book/title' -n catalog.xml # → 1984 # → Dune