Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java XML namespaces: select by URI and local name

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

An XML namespace prefix is a document-local abbreviation. Code that identifies an element should use its namespace URI and local name, not depend on the sender's chosen prefix.

Operational contract

The method selects receipt elements by namespace URI and local name from a namespace-aware Document, then reads their unqualified id attributes. It rejects more than 47 matches. getElementsByTagNameNS finds descendants, so the caller must also validate the expected tree shape if only direct children are allowed. The namespace URI passed to this method is an identifier; the code does not dereference it. The parser boundary still decides whether external resources can be opened and how much input is accepted.

Failure case

One carrier writes a prefix 'c' and another uses 'shipment' for the same namespace URI. Both represent the same receipt element name. A prefix-based string comparison would produce different results; this method does not. A receipt nested in an unexpected wrapper still needs structural validation rather than being accepted solely because its namespace matches.

Java code

Java
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class NamespacedReceiptIds {
    public static List<String> select(Document manifest, String namespaceUri) {
        NodeList receipts = manifest.getElementsByTagNameNS(namespaceUri, "receipt");
        if (receipts.getLength() > 47) throw new IllegalArgumentException("Too many receipts");
        List<String> ids = new ArrayList<>();
        for (int index = 0; index < receipts.getLength(); index++) {
            Element receipt = (Element) receipts.item(index);
            ids.add(receipt.getAttribute("id"));
        }
        return ids;
    }
}

Performance and ownership cost

The DOM search visits matching tree regions and may scan O(N) nodes; the result list is O(R) for R matches. The DOM remains the larger memory cost. Repeated whole-tree searches should be measured before replacing one pass with many queries.

Common Mistakes

  • Do not compare namespace prefixes as global identities.
  • Do not assume descendant selection enforces direct-child placement.
  • Do not infer that a namespace URI is a resource the parser should fetch.

Connected lessons

java
xml processing boundaries
xml-namespace-uri-selection
Storage details