XPath Tester
Teste XPath-Ausdrücke gegen XML und sehe alle übereinstimmenden Knoten
XML-Eingabe
Was ist XPath?
XPath (XML Path Language) ist eine Abfragesprache zum Auswählen von Knoten aus einem XML-Dokument. Vom W3C als Teil des XSLT-Standards definiert, behandelt XPath ein XML-Dokument als Knotenbaum und bietet eine pfadbasierte Syntax zur Navigation in diesem Baum. Ein XPath-Ausdruck wie //book[@category="fiction"]/title wählt jedes title-Element innerhalb eines book-Elements aus, dessen category-Attribut den Wert "fiction" hat. XPath 1.0, die von allen gängigen Browsern und den meisten XML-Bibliotheken unterstützte Version, wurde 1999 als W3C-Empfehlung veröffentlicht und ist nach wie vor die am weitesten verbreitete Version.
XPath-Ausdrücke liefern einen von vier Ergebnistypen: Node-Sets, Strings, Zahlen oder Booleans. Ein Node-Set ist das häufigste Ergebnis und enthält null oder mehr XML-Knoten (Elemente, Attribute, Textknoten, Kommentare oder Verarbeitungsanweisungen). String-, Zahlen- und Boolean-Ergebnisse stammen aus XPath-Funktionen wie count(), sum(), contains() und booleschen Vergleichen. Dieses Typsystem macht XPath sowohl für die Datenextraktion als auch für das Schreiben bedingter Logik in XSLT-Stylesheets und XML-Schema-Assertions geeignet.
Version-1.0-Ausdrücke funktionieren überall: in JavaScript über document.evaluate(), in Python über lxml und ElementTree, in Java über javax.xml.xpath, in PHP über DOMXPath und in Kommandozeilen-Tools wie xmllint. Die Versionen 2.0 und 3.1 bieten reichhaltigere Typsysteme und Funktionen, erfordern aber dedizierte Engines wie Saxon. Verwenden Sie standardmäßig Version 1.0. Greifen Sie auf 2.0 oder 3.1 nur zurück, wenn Sie Sequenzen, reguläre Ausdrücke oder Higher-Order-Funktionen benötigen — und nehmen Sie dann die Abhängigkeit von Saxon oder BaseX in Kauf.
Warum einen Online-XPath-Tester verwenden?
Korrekte Ausdrücke zu schreiben erfordert ein Verständnis der Dokumentstruktur und Tests mit echten Daten. Das Tool bietet eine interaktive Umgebung, um Ausdrücke iterativ zu entwickeln, ohne ein Projekt aufzusetzen oder Boilerplate-Code zu schreiben.
Anwendungsfälle für den XPath Tester
XPath-Achsen-Referenz
Eine Achse definiert die Navigationsrichtung relativ zum aktuellen (Kontext-)Knoten. Die vollständige Syntax lautet axis::node-test[predicate], obwohl die meisten Entwickler täglich die abgekürzten Formen (//, @, ..) verwenden. Diese Tabelle listet alle 1.0-Achsen mit praktischen Beispielen auf.
| Achse | Beispiel | Beschreibung |
|---|---|---|
| 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-Funktionen
Die Sprache definiert 27 eingebaute Funktionen in vier Kategorien: Node-Set, String, Zahl und Boolean. Dies sind die Funktionen, die Sie beim Schreiben von Abfragen am häufigsten verwenden werden. Alle werden von diesem Tester und von jeder konformen Implementierung unterstützt.
| Funktion | Kategorie | Beschreibung |
|---|---|---|
| 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 |
Code-Beispiele
Diese Beispiele zeigen, wie Ausdrücke programmatisch ausgewertet werden. Jeder Code-Ausschnitt verwendet dieselbe catalog.xml-Struktur, sodass Sie die API-Unterschiede zwischen den Sprachen vergleichen können.
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