Taskcore
Query XML with XPath
Also called XPath query, select XML nodes, find elements in XML.
Parse an XML text, evaluate an XPath path from the root element with a map of namespace prefixes, and return the string value of each selected element in document order.
- Evidence
- Code in 3 languages
Task
Find parts of an XML document with an XPath expression. Each solution is a function query_xpath(text, path, namespaces) that parses the text, evaluates the path with the root element as the context node, and returns the string value of each selected element, in document order.
The path is in the abbreviated syntax of XPath 1.0 (see XPath). The contract uses the part of the syntax that all three standard libraries on this page support:
book/titleselects thetitlechildren of thebookchildren of the root, and.//titleselects alltitleelements under the root. A*as the last step selects all child elements.- A step can have one predicate:
[@year]and[@year='2008']test an attribute,[note]and[title='Beta']test a child,[.='Beta']tests the element itself, and[2]and[last()]select by position among the children of each parent. - A name with a prefix, such as
m:lang, is in the namespace that the mapnamespacesgives for the prefix. A name with no prefix is in no namespace.
The string value of an element is all the text inside it, also the text of its child elements. For <title>Be<i>ta</i></title> it is Beta. Entity references such as & are replaced, and comments are not part of it.
The solution reports parse-error when the text is not well-formed XML, and bad-path when the path is not valid or uses a prefix that is not in the map.
Solutions
Python, Java and C# have XPath in the standard library. The standard libraries of Go, JavaScript (Node.js), TypeScript, Rust, C, C++ and Bash do not, and matrix.yaml names the usual libraries.
- Python.
ElementTree.findalltakes a path and a namespace map. The documentation is clear about the limits: "The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module."1findall"Returns a list containing all matching elements in document order", and itsnamespacesargument "is an optional mapping from namespace prefix to full name."1 The solution joinsitertext()to get the string value. For full XPath 1.0 in Python, use the library lxml: itsxpath()method takes anamespacesdictionary that "maps the namespace prefixes used in the XPath expression to namespace URIs"2. - Java. "The XPath API supports XML Path Language (XPath) Version 1.0"3. The solution parses with a namespace-aware
DocumentBuilderFactoryand evaluates the path withXPath.evaluateandXPathConstants.NODESET. ANamespaceContextgives the prefixes: "QNames in the expression are resolved against the XPath namespace context set with setNamespaceContext(NamespaceContext nsContext)."4getTextContentgives the string value. - C#. The extension method
XPathSelectElementson LINQ to XML takes anIXmlNamespaceResolver"for the namespace prefixes in the XPath expression"5, and anXmlNamespaceManageris one.XElement.Valuegives the string value.
All three solutions refuse a document type declaration. Java needs the feature disallow-doctype-decl for this. In .NET, the default of XmlReaderSettings.DtdProcessing already "is Prohibit"6.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Most cases use one small library document with three books, where the third book is in a shelf element.
first-of-each-parentandlast-of-each-parent:.//book[1]gives the firstbookof the root and the firstbookof the shelf, not one book. The position counts among the children of each parent.attribute-not-equal:[@m:lang!='en']is false for a book with nom:langattribute, because a comparison with an empty node-set is false.has-attributeandhas-child: a predicate with only a name tests that the attribute or the child exists.self,cdata-and-entitiesandcomment-in-text: the string value joins the text of child elements, replaces<and&, keeps the text of a CDATA section and drops comments.default-namespace-unprefixed,default-namespace-prefixedandother-prefix: in a document with a default namespace,bookselects nothing andb:bookwithbbound to the namespace selects the book. The prefix in the path need not be the prefix in the document.empty-elements,no-match,whitespaceandnon-ascii: an empty element has the value"", a path that matches nothing gives[], spaces are kept, and the values can hold any Unicode text.
cases/errors.jsonl lists the texts that are not XML and the paths that are not valid. The toolchain does not load this file yet, so each test file holds these cases by name.
Pitfalls
- Building the path from user input. OWASP describes the attack: "Similar to SQL Injection, XPath Injection attacks occur when a web site uses user-supplied information to construct an XPath query for XML data."7 The defense is the same as for SQL: "use a parameterized XPath interface if one is available, or escape the user input"7. In Java, a variable such as
$namein the path takes its value from anXPathVariableResolver4, and lxml takes variables as keyword arguments2:
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Main {
static void show(String label, NodeList nodes) {
StringBuilder out = new StringBuilder(label + ":");
for (int i = 0; i < nodes.getLength(); i++) {
out.append(' ').append(nodes.item(i).getTextContent());
}
System.out.println(out);
}
public static void main(String[] args) throws Exception {
String text = "<users><user><name>ada</name><role>admin</role></user>"
+ "<user><name>bob</name><role>guest</role></user></users>";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(text)));
XPath xp = XPathFactory.newInstance().newXPath();
String name = "x' or 'a'='a";
// Wrong: the input becomes part of the expression.
String built = "/users/user[name='" + name + "']/role";
System.out.println(built);
show("concatenated", (NodeList) xp.evaluate(built, doc, XPathConstants.NODESET));
// Right: the input is the value of the variable $name.
xp.setXPathVariableResolver(q -> q.getLocalPart().equals("name") ? name : null);
show("variable", (NodeList) xp.evaluate("/users/user[name=$name]/role", doc, XPathConstants.NODESET));
}
}
/users/user[name='x' or 'a'='a']/role
concatenated: admin guest
variable:
- A parser that is not namespace-aware. The Java
DocumentBuilderFactoryis not namespace-aware: "By default the value of this is set to false"8. WithoutsetNamespaceAware(true), the elements have no namespace, and a path with a prefix finds nothing. - Default namespaces. A path with
bookfinds nothing in a document with a default namespace. Bind a prefix to the namespace and writeb:book. In Python, a map entry with the empty prefix also works for ElementTree: "Pass '' as prefix to move all unprefixed tag names in the expression into the given namespace."1 This is an extension of ElementTree, and XPath 1.0 has no such rule. - ElementTree errors. ElementTree raises
SyntaxErrorfor most bad paths, but a predicate with no closing bracket gives aTypeErrorin Python 3.12 and 3.14:
import xml.etree.ElementTree as ET
root = ET.fromstring("<a><b/></a>")
for path in ["b[0]", "/a/b", "b[position()=1]", "b["]:
try:
print(path, root.findall(path))
except Exception as error:
print(path, type(error).__name__)
b[0] SyntaxError
/a/b SyntaxError
b[position()=1] SyntaxError
b[ TypeError
The solution catches both. A path that is valid XPath 1.0 but outside the subset, such as /a/b or b[position()=1], also fails in ElementTree. For an attribute value test, "The value cannot contain quotes."1
- Shared XPath objects in Java. "An XPath object is not thread-safe and not reentrant."4 Make one for each thread, or one for each call, as the solution does.
text()is not the string value. In full XPath,title/text()selects the text nodes, and<title>Be<i>ta</i></title>has only the text nodeBe. The string valueBetajoins all the descendant text.
Related tasks
- Read and write XML parses XML to a tree and writes it back.
- Validate data against a schema checks that a document has the structure that a schema describes.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/query-xml-with-xpath/.
import xml.etree.ElementTree as ET
class QueryError(ValueError):
"""The text is not well-formed XML (parse-error), or the path is not valid (bad-path)."""
def __init__(self, kind: str, detail: str) -> None:
super().__init__(f"{kind}: {detail}")
self.kind = kind
def query_xpath(text: str, path: str, namespaces: dict[str, str]) -> list[str]:
"""Returns the string value of each element that the path selects from the root element, in document order."""
try:
root = ET.fromstring(text)
except ET.ParseError as error:
raise QueryError("parse-error", str(error)) from error
try:
# findall supports the subset of XPath 1.0 of the contract. A prefix in the path is looked up in namespaces.
elements = root.findall(path, namespaces)
except (SyntaxError, TypeError) as error:
# ElementTree raises SyntaxError for most bad paths, and TypeError for a predicate with no closing bracket.
raise QueryError("bad-path", str(error)) from error
# The string value of an element is all of its descendant text, as in XPath.
return ["".join(element.itertext()) for element in elements]
test_query_xpath.py 67 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/query-xml-with-xpath/.
import pytest
from query_xpath import QueryError, query_xpath
LIBRARY = (
"<library xmlns:m=\"urn:example:meta\">"
"<book id=\"b1\" year=\"1999\" m:lang=\"en\"><title>Alpha</title><price>12.50</price></book>"
"<book id=\"b2\" year=\"2008\"><title>Beta</title><price>30.00</price><note>out of print</note></book>"
"<shelf>"
"<book id=\"b3\" year=\"2008\" m:lang=\"fr\"><title>Gamma</title><price>8.25</price></book>"
"</shelf>"
"</library>"
)
BOOKS = "<library xmlns=\"urn:example:books\"><book>Alpha</book></library>"
META = {"m": "urn:example:meta"}
# name: (text, path, namespaces, the string values)
CASES = {
"child-path": (LIBRARY, "book/title", {}, ["Alpha", "Beta"]),
"descendants": (LIBRARY, ".//title", {}, ["Alpha", "Beta", "Gamma"]),
"attribute-equals": (LIBRARY, ".//book[@year='2008']/title", {}, ["Beta", "Gamma"]),
"child-equals": (LIBRARY, "book[title='Beta']/price", {}, ["30.00"]),
"position": (LIBRARY, "book[2]/title", {}, ["Beta"]),
"has-attribute": (LIBRARY, ".//book[@m:lang]/title", META, ["Alpha", "Gamma"]),
"attribute-not-equal": (LIBRARY, ".//book[@m:lang!='en']/title", META, ["Gamma"]),
"has-child": (LIBRARY, "book[note]/title", {}, ["Beta"]),
"first-of-each-parent": (LIBRARY, ".//book[1]/title", {}, ["Alpha", "Gamma"]),
"last-of-each-parent": (LIBRARY, ".//book[last()]/title", {}, ["Beta", "Gamma"]),
"wildcard": (LIBRARY, "book[1]/*", {}, ["Alpha", "12.50"]),
"descendant-wildcard": ("<r><a>1<b>2</b></a><c>3</c></r>", ".//*", {}, ["12", "2", "3"]),
"no-match": (LIBRARY, "book/author", {}, []),
"self": ("<p>Tom <b>&</b> Jerry</p>", ".", {}, ["Tom & Jerry"]),
"cdata-and-entities": ("<r><x><![CDATA[a<b]]></x><x><c></x></r>", "x", {}, ["a<b", "<c>"]),
"comment-in-text": ("<r><v>a<!-- note -->b</v></r>", "v", {}, ["ab"]),
"empty-elements": ("<r><v/><v></v></r>", "v", {}, ["", ""]),
"default-namespace-unprefixed": (BOOKS, "book", {}, []),
"default-namespace-prefixed": (BOOKS, "b:book", {"b": "urn:example:books"}, ["Alpha"]),
"other-prefix": ("<x:list xmlns:x=\"urn:k\"><x:item>1</x:item></x:list>", "k:item", {"k": "urn:k"}, ["1"]),
"whitespace": ("<r>\n <v> a </v>\n</r>", "v", {}, [" a "]),
"non-ascii": ("<r><city>Zürich</city><city>東京</city></r>", "city[.='東京']", {}, ["東京"]),
}
# name: (text, path, namespaces, the kind of error)
INVALID = {
"not-well-formed": ("<a><b></a>", "b", {}, "parse-error"),
"empty-text": ("", "b", {}, "parse-error"),
"unbound-prefix-in-text": ("<x:a/>", "b", {}, "parse-error"),
"unclosed-predicate": (LIBRARY, "book[@id='b1'", {}, "bad-path"),
"unbound-prefix-in-path": (LIBRARY, "x:book", {}, "bad-path"),
}
@pytest.mark.parametrize("name", CASES)
def test_cases(name: str) -> None:
text, path, namespaces, want = CASES[name]
assert query_xpath(text, path, namespaces) == want
@pytest.mark.parametrize("name", INVALID)
def test_errors(name: str) -> None:
text, path, namespaces, kind = INVALID[name]
with pytest.raises(QueryError) as info:
query_xpath(text, path, namespaces)
assert info.value.kind == kind
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/query-xml-with-xpath/.
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public final class QueryXpath {
/** The text is not well-formed XML (parse-error), or the path is not valid (bad-path). */
public static final class QueryException extends Exception {
private static final long serialVersionUID = 1L;
public final String kind;
QueryException(String kind, Throwable cause) {
super(kind + ": " + cause.getMessage(), cause);
this.kind = kind;
}
}
private QueryXpath() {}
/** Returns the string value of each element that the path selects from the root element, in document order. */
public static List<String> queryXpath(String text, String path, Map<String, String> namespaces)
throws QueryException {
Document doc;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Without this, the parser gives no namespace to any element, and a prefix in the path never matches.
factory.setNamespaceAware(true);
// A document type declaration can define entities that read files; the contract has none, so refuse it.
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder builder = factory.newDocumentBuilder();
// The default error handler prints each fatal error to System.err; DefaultHandler only throws it.
builder.setErrorHandler(new DefaultHandler());
doc = builder.parse(new InputSource(new StringReader(text)));
} catch (SAXException | IOException e) {
throw new QueryException("parse-error", e);
} catch (ParserConfigurationException e) {
throw new IllegalStateException(e);
}
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
// An unknown prefix maps to no namespace, and the evaluation then fails.
return namespaces.getOrDefault(prefix, XMLConstants.NULL_NS_URI);
}
@Override
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
@Override
public Iterator<String> getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
});
NodeList nodes;
try {
nodes = (NodeList) xpath.evaluate(path, doc.getDocumentElement(), XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new QueryException("bad-path", e);
}
List<String> values = new ArrayList<>();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
// getTextContent joins the text of all descendants and skips comments, as the XPath string value does.
values.add(node.getTextContent());
}
return values;
}
}
QueryXpathTest.java 97 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/query-xml-with-xpath/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class QueryXpathTest {
static final String LIBRARY =
"<library xmlns:m=\"urn:example:meta\">"
+ "<book id=\"b1\" year=\"1999\" m:lang=\"en\"><title>Alpha</title><price>12.50</price></book>"
+ "<book id=\"b2\" year=\"2008\"><title>Beta</title><price>30.00</price><note>out of print</note></book>"
+ "<shelf>"
+ "<book id=\"b3\" year=\"2008\" m:lang=\"fr\"><title>Gamma</title><price>8.25</price></book>"
+ "</shelf>"
+ "</library>";
static final String BOOKS = "<library xmlns=\"urn:example:books\"><book>Alpha</book></library>";
static final Map<String, String> META = Map.of("m", "urn:example:meta");
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("child-path", LIBRARY, "book/title", Map.of(),
List.of("Alpha", "Beta")),
Arguments.of("descendants", LIBRARY, ".//title", Map.of(),
List.of("Alpha", "Beta", "Gamma")),
Arguments.of("attribute-equals", LIBRARY, ".//book[@year='2008']/title", Map.of(),
List.of("Beta", "Gamma")),
Arguments.of("child-equals", LIBRARY, "book[title='Beta']/price", Map.of(),
List.of("30.00")),
Arguments.of("position", LIBRARY, "book[2]/title", Map.of(),
List.of("Beta")),
Arguments.of("has-attribute", LIBRARY, ".//book[@m:lang]/title", META,
List.of("Alpha", "Gamma")),
Arguments.of("attribute-not-equal", LIBRARY, ".//book[@m:lang!='en']/title", META,
List.of("Gamma")),
Arguments.of("has-child", LIBRARY, "book[note]/title", Map.of(),
List.of("Beta")),
Arguments.of("first-of-each-parent", LIBRARY, ".//book[1]/title", Map.of(),
List.of("Alpha", "Gamma")),
Arguments.of("last-of-each-parent", LIBRARY, ".//book[last()]/title", Map.of(),
List.of("Beta", "Gamma")),
Arguments.of("wildcard", LIBRARY, "book[1]/*", Map.of(),
List.of("Alpha", "12.50")),
Arguments.of("descendant-wildcard", "<r><a>1<b>2</b></a><c>3</c></r>", ".//*", Map.of(),
List.of("12", "2", "3")),
Arguments.of("no-match", LIBRARY, "book/author", Map.of(),
List.of()),
Arguments.of("self", "<p>Tom <b>&</b> Jerry</p>", ".", Map.of(),
List.of("Tom & Jerry")),
Arguments.of("cdata-and-entities", "<r><x><![CDATA[a<b]]></x><x><c></x></r>", "x", Map.of(),
List.of("a<b", "<c>")),
Arguments.of("comment-in-text", "<r><v>a<!-- note -->b</v></r>", "v", Map.of(),
List.of("ab")),
Arguments.of("empty-elements", "<r><v/><v></v></r>", "v", Map.of(),
List.of("", "")),
Arguments.of("default-namespace-unprefixed", BOOKS, "book", Map.of(),
List.of()),
Arguments.of("default-namespace-prefixed", BOOKS, "b:book", Map.of("b", "urn:example:books"),
List.of("Alpha")),
Arguments.of("other-prefix", "<x:list xmlns:x=\"urn:k\"><x:item>1</x:item></x:list>", "k:item", Map.of("k", "urn:k"),
List.of("1")),
Arguments.of("whitespace", "<r>\n <v> a </v>\n</r>", "v", Map.of(),
List.of(" a ")),
Arguments.of("non-ascii", "<r><city>Zürich</city><city>東京</city></r>", "city[.='東京']", Map.of(),
List.of("東京")));
}
static Stream<Arguments> errors() {
return Stream.of(
Arguments.of("not-well-formed", "<a><b></a>", "b", Map.of(), "parse-error"),
Arguments.of("empty-text", "", "b", Map.of(), "parse-error"),
Arguments.of("unbound-prefix-in-text", "<x:a/>", "b", Map.of(), "parse-error"),
Arguments.of("unclosed-predicate", LIBRARY, "book[@id='b1'", Map.of(), "bad-path"),
Arguments.of("unbound-prefix-in-path", LIBRARY, "x:book", Map.of(), "bad-path"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void selects(String name, String text, String path, Map<String, String> namespaces, List<String> want)
throws QueryXpath.QueryException {
assertEquals(want, QueryXpath.queryXpath(text, path, namespaces), name);
}
@ParameterizedTest(name = "{0}")
@MethodSource("errors")
void reports(String name, String text, String path, Map<String, String> namespaces, String kind) {
QueryXpath.QueryException e = assertThrows(
QueryXpath.QueryException.class, () -> QueryXpath.queryXpath(text, path, namespaces), name);
assertEquals(kind, e.kind, name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/query-xml-with-xpath/.
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
// The text is not well-formed XML (parse-error), or the path is not valid (bad-path).
public sealed class QueryException(string kind, Exception inner) : Exception($"{kind}: {inner.Message}", inner)
{
public string Kind { get; } = kind;
}
public static class QueryXpath
{
// Returns the string value of each element that the path selects from the root element, in document order.
public static List<string> Query(string text, string path, IReadOnlyDictionary<string, string> namespaces)
{
XDocument doc;
try
{
// A document type declaration can define entities; the contract has none, so the reader refuses it.
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit };
using var reader = XmlReader.Create(new StringReader(text), settings);
doc = XDocument.Load(reader);
}
catch (XmlException e)
{
throw new QueryException("parse-error", e);
}
// The prefixes of the path are bound here, not by the document.
var manager = new XmlNamespaceManager(new NameTable());
foreach (var (prefix, uri) in namespaces)
{
manager.AddNamespace(prefix, uri);
}
try
{
// Value joins the text of all descendants and skips comments, as the XPath string value does.
return doc.Root!.XPathSelectElements(path, manager).Select(element => element.Value).ToList();
}
catch (XPathException e)
{
throw new QueryException("bad-path", e);
}
}
}
QueryXpathTests.cs 75 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/query-xml-with-xpath/.
using Xunit;
public sealed class QueryXpathTests
{
private const string Library =
"<library xmlns:m=\"urn:example:meta\">"
+ "<book id=\"b1\" year=\"1999\" m:lang=\"en\"><title>Alpha</title><price>12.50</price></book>"
+ "<book id=\"b2\" year=\"2008\"><title>Beta</title><price>30.00</price><note>out of print</note></book>"
+ "<shelf>"
+ "<book id=\"b3\" year=\"2008\" m:lang=\"fr\"><title>Gamma</title><price>8.25</price></book>"
+ "</shelf>"
+ "</library>";
private const string Books = "<library xmlns=\"urn:example:books\"><book>Alpha</book></library>";
// The namespaces are "prefix=uri" pairs joined by "|", so that TheoryData can hold them.
private static Dictionary<string, string> Namespaces(string pairs) =>
pairs.Split('|', StringSplitOptions.RemoveEmptyEntries)
.Select(pair => pair.Split('=', 2))
.ToDictionary(pair => pair[0], pair => pair[1]);
// case, text, path, namespaces, the string values
public static TheoryData<string, string, string, string, string[]> Cases => new()
{
{ "child-path", Library, "book/title", "", ["Alpha", "Beta"] },
{ "descendants", Library, ".//title", "", ["Alpha", "Beta", "Gamma"] },
{ "attribute-equals", Library, ".//book[@year='2008']/title", "", ["Beta", "Gamma"] },
{ "child-equals", Library, "book[title='Beta']/price", "", ["30.00"] },
{ "position", Library, "book[2]/title", "", ["Beta"] },
{ "has-attribute", Library, ".//book[@m:lang]/title", "m=urn:example:meta", ["Alpha", "Gamma"] },
{ "attribute-not-equal", Library, ".//book[@m:lang!='en']/title", "m=urn:example:meta", ["Gamma"] },
{ "has-child", Library, "book[note]/title", "", ["Beta"] },
{ "first-of-each-parent", Library, ".//book[1]/title", "", ["Alpha", "Gamma"] },
{ "last-of-each-parent", Library, ".//book[last()]/title", "", ["Beta", "Gamma"] },
{ "wildcard", Library, "book[1]/*", "", ["Alpha", "12.50"] },
{ "descendant-wildcard", "<r><a>1<b>2</b></a><c>3</c></r>", ".//*", "", ["12", "2", "3"] },
{ "no-match", Library, "book/author", "", [] },
{ "self", "<p>Tom <b>&</b> Jerry</p>", ".", "", ["Tom & Jerry"] },
{ "cdata-and-entities", "<r><x><![CDATA[a<b]]></x><x><c></x></r>", "x", "", ["a<b", "<c>"] },
{ "comment-in-text", "<r><v>a<!-- note -->b</v></r>", "v", "", ["ab"] },
{ "empty-elements", "<r><v/><v></v></r>", "v", "", ["", ""] },
{ "default-namespace-unprefixed", Books, "book", "", [] },
{ "default-namespace-prefixed", Books, "b:book", "b=urn:example:books", ["Alpha"] },
{ "other-prefix", "<x:list xmlns:x=\"urn:k\"><x:item>1</x:item></x:list>", "k:item", "k=urn:k", ["1"] },
{ "whitespace", "<r>\n <v> a </v>\n</r>", "v", "", [" a "] },
{ "non-ascii", "<r><city>Zürich</city><city>東京</city></r>", "city[.='東京']", "", ["東京"] },
};
// case, text, path, namespaces, the kind of error
public static TheoryData<string, string, string, string, string> Errors => new()
{
{ "not-well-formed", "<a><b></a>", "b", "", "parse-error" },
{ "empty-text", "", "b", "", "parse-error" },
{ "unbound-prefix-in-text", "<x:a/>", "b", "", "parse-error" },
{ "unclosed-predicate", Library, "book[@id='b1'", "", "bad-path" },
{ "unbound-prefix-in-path", Library, "x:book", "", "bad-path" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Selects(string name, string text, string path, string namespaces, string[] want)
{
Assert.True(want.SequenceEqual(QueryXpath.Query(text, path, Namespaces(namespaces))), name);
}
[Theory]
[MemberData(nameof(Errors))]
public void Reports(string name, string text, string path, string namespaces, string kind)
{
var e = Assert.Throws<QueryException>(() => QueryXpath.Query(text, path, Namespaces(namespaces)));
Assert.True(kind == e.Kind, name);
}
}
References
- The Python Standard Library, xml.etree.ElementTree, Python 3.14, XPath support; Supported XPath syntax; Element.findall
- lxml, XPath and XSLT with lxml, The xpath() method; Namespaces and prefixes
- Java SE 25 API, package javax.xml.xpath, 1 XPath Overview; 3 XPath Data Types
- Java SE 25 API, javax.xml.xpath.XPath, the interface description (QNames; thread safety); setNamespaceContext; setXPathVariableResolver
- .NET API documentation, Extensions.XPathSelectElements Method, XPathSelectElements(XNode, String, IXmlNamespaceResolver)
- .NET API documentation, XmlReaderSettings.DtdProcessing Property, Property Value
- OWASP Community, XPATH Injection, Description; XPath Injection Defenses
- Java SE 25 API, javax.xml.parsers.DocumentBuilderFactory, setNamespaceAware
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (csharp) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 8K94Q0 Edit this page History Report an error Markdown