XPath Tester
Test XPath-expressies op XML en bekijk alle overeenkomende knooppunten
XML-invoer
Wat is XPath?
XPath (XML Path Language) is een querytaal voor het selecteren van knooppunten uit een XML-document. Gedefinieerd door het W3C als onderdeel van de XSLT-standaard, beschouwt XPath een XML-document als een boom van knooppunten en biedt het een padgebaseerde syntaxis om door die boom te navigeren. Een XPath-expressie zoals //book[@category="fiction"]/title selecteert elk title-element binnen een book-element waarvan het category-attribuut gelijk is aan "fiction". XPath 1.0, de versie die door alle grote browsers en de meeste XML-bibliotheken wordt ondersteund, werd in 1999 gepubliceerd als W3C Recommendation en blijft de meest toegepaste versie.
XPath-expressies retourneren een van vier resultaattypen: knooppuntsets, tekenreeksen, getallen of booleans. Een knooppuntset is het meest voorkomende resultaat en bevat nul of meer XML-knooppunten (elementen, attributen, tekstknooppunten, opmerkingen of verwerkingsinstructies). Tekenreeks-, getal- en booleanresultaten zijn afkomstig van XPath-functies zoals count(), sum(), contains() en booleaanse vergelijkingen. Dit typesysteem maakt XPath geschikt voor zowel het extraheren van gegevens als het schrijven van conditionele logica in XSLT-stylesheets en XML Schema-assertions.
Versie 1.0-expressies werken overal: document.evaluate() in JavaScript, lxml en ElementTree in Python, javax.xml.xpath in Java, DOMXPath in PHP en opdrachtregelprogramma's zoals xmllint. Versies 2.0 en 3.1 voegen rijkere typesystemen en functies toe, maar vereisen speciale engines zoals Saxon. Gebruik standaard versie 1.0. Grijp naar 2.0 of 3.1 alleen wanneer u sequences, reguliere expressies of hogere-ordefuncties nodig hebt — en aanvaard dan de afhankelijkheid van Saxon of BaseX.
Waarom een online XPath Tester gebruiken?
Het schrijven van correcte expressies vereist inzicht in de documentstructuur en testen met echte gegevens. Dit hulpmiddel biedt een interactieve omgeving om expressies te verfijnen zonder een project op te zetten of standaardcode te schrijven.
Toepassingen van de XPath Tester
Naslaginformatie XPath-assen
Een as definieert de navigatierichting ten opzichte van het huidige (context)knooppunt. De volledige syntaxis is as::knooppunttest[predikaat], hoewel de meeste ontwikkelaars dagelijks de verkorte vormen (//, @, ..) gebruiken. Deze tabel geeft een overzicht van alle 1.0-assen met praktische voorbeelden.
| As | Voorbeeld | Beschrijving |
|---|---|---|
| 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 |
XPath 1.0-functies
De taal definieert 27 ingebouwde functies in vier categorieën: knooppuntset, tekenreeks, getal en boolean. Dit zijn de functies die u het vaakst gebruikt bij het schrijven van query's. Alle functies worden ondersteund door dit hulpmiddel en door elke conforme implementatie.
| Functie | Categorie | Beschrijving |
|---|---|---|
| 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 |
Codevoorbeelden
Deze voorbeelden laten zien hoe u expressies programmatisch kunt evalueren. Elk codefragment gebruikt dezelfde catalog.xml-structuur, zodat u de API-verschillen tussen talen kunt vergelijken.
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