XPath selects nodes from an XML tree. A fixed expression is a known application rule; concatenating user text into an XPath expression changes that rule.
Java XPath: compile a fixed selection, not user-supplied code
Operational contract
The method evaluates a static path against a Document that the caller has already parsed under an external-access and size policy. It extracts receipt IDs from attribute nodes and caps the result at 47. NodeList retains references into the DOM tree, so the document remains reachable during extraction. The expression is not a general-purpose search feature; if a user needs a filter, select the known nodes first and compare their values in Java. Namespaces require an explicit NamespaceContext or namespace-aware DOM selection rather than guessing prefixes.
Failure case
An audit asks for receipt IDs in the top-level manifest collection. A fixed path returns those IDs. If a user submits a receipt ID containing brackets or quotes, that input belongs in a value comparison, not in the XPath source. A malformed or unexpected tree yields an empty result that the caller must distinguish from an approved empty manifest.
Java code
import java.util.ArrayList;
import java.util.List;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class ManifestXPathIds {
public static List<String> receiptIds(Document manifest) throws Exception {
XPathExpression selection = XPathFactory.newInstance().newXPath()
.compile("/manifest/receipt/@id");
NodeList attributes = (NodeList) selection.evaluate(manifest, XPathConstants.NODESET);
if (attributes.getLength() > 47) throw new IllegalArgumentException("Too many receipts");
List<String> ids = new ArrayList<>();
for (int index = 0; index < attributes.getLength(); index++) {
ids.add(attributes.item(index).getNodeValue());
}
return ids;
}
}Performance and ownership cost
XPath evaluation traverses the relevant DOM nodes and can cost O(N) or more according to expression and implementation; result storage is O(R) for R selected IDs. This static expression is simple, but the DOM itself still has O(document) retention.
Common Mistakes
- Do not concatenate user data into an XPath program.
- Do not assume an empty selection proves the input was valid.
- Do not treat a prefix spelling as a namespace identity.
Connected lessons
- Java DOM parsing: deny external XML access at the factory
- Java XML namespaces: select by URI and local name
- Java Pattern.quote: match a supplied token literally
- Java StAX: pull XML events under a count and entity policy
- Java XML Schema validation: use a trusted schema without external fetches
- Java XML Transformer: bound serialized output and external access
- Java XML and archive boundaries quiz
- Advanced Java
