import { Expression, Matcher } from 'path-expression-matcher';// Create expression (parse once, reuse many times)const expr = new Expression("root.users.user");// Create matcher (tracks current path)const matcher = new Matcher();matcher.push("root");matcher.push("users");matcher.push("user", { id: "123" });// Match current path against expressionif (matcher.matches(expr)) { console.log("Match found!"); console.log("Current path:", matcher.toString()); // "root.users.user"}// Namespace supportconst nsExpr = new Expression("soap::Envelope.soap::Body..ns::UserId");matcher.push("Envelope", null, "soap");matcher.push("Body", null, "soap");matcher.push("UserId", null, "ns");console.log(matcher.toString()); // "soap:Envelope.soap:Body.ns:UserId"
📖 Pattern Syntax
Basic Paths
"root.users.user" // Exact path match"*.users.user" // Wildcard: any parent"root.*.user" // Wildcard: any middle"root.users.*" // Wildcard: any child
Deep Wildcard
"..user" // user anywhere in tree"root..user" // user anywhere under root"..users..user" // users somewhere, then user below it
Attribute Matching
"user[id]" // user with "id" attribute"user[type=admin]" // user with type="admin" (current node only)
Note: Attribute conditions in expressions only ever look at the current (last) node in the path — ..user matches user at any depth, but bracket conditions like [lang] still apply to user itself, never to an ancestor tag. To check an ancestor's attribute (e.g. "is there a lang attribute somewhere above this node?"), use push(..., { keep: [...] }) with getAnyParentAttr() / hasAnyParentAttr() — see Ancestor Attributes (keep) below.
Position Selectors
"user:first" // First user (counter=0)"user:nth(2)" // Third user (counter=2, zero-based)"user:odd" // Odd-numbered users (counter=1,3,5...)"user:even" // Even-numbered users (counter=0,2,4...)"root.users.user:first" // First user under users
Note: Position selectors use the counter (occurrence count of the tag name), not the position (child index). For example, in <root><a/><b/><a/></root>, the second <a/> has position=2 but counter=1.
Namespaces
"ns::user" // user with namespace "ns""soap::Envelope" // Envelope with namespace "soap""ns::user[id]" // user with namespace "ns" and "id" attribute"ns::user:first" // First user with namespace "ns""*::user" // user with any namespace"..ns::item" // item with namespace "ns" anywhere in tree"soap::Envelope.soap::Body" // Nested namespaced elements"ns::first" // Tag named "first" with namespace "ns" (NO ambiguity!)
Namespace syntax:
Use double colon (::) for namespace: ns::tag
Use single colon (:) for position: tag:first
Combined: ns::tag:first (namespace + tag + position)
Namespace matching rules:
Pattern ns::user matches only nodes with namespace "ns" and tag "user"
Pattern user (no namespace) matches nodes with tag "user" regardless of namespace
Pattern *::user matches tag "user" with any namespace (wildcard namespace)
Namespaces are tracked separately for counter/position (e.g., ns1::item and ns2::item have independent counters)
Wildcard Differences
Single wildcard (*) - Matches exactly ONE level:
"*.fix1" matches root.fix1 (2 levels) ✅
"*.fix1" does NOT match root.another.fix1 (3 levels) ❌
Path depth MUST equal pattern depth
Deep wildcard (..) - Matches ZERO or MORE levels:
"..fix1" matches root.fix1 ✅
"..fix1" matches root.another.fix1 ✅
"..fix1" matches a.b.c.d.fix1 ✅
Works at any depth
Combined Patterns
"..user[id]:first" // First user with id, anywhere"root..user[type=admin]" // Admin user under root"ns::user[id]:first" // First namespaced user with id"soap::Envelope..ns::UserId" // UserId with namespace ns under SOAP envelope
namespace (string, optional): Namespace for the tag
options (object, optional):
keep (string[], optional): Names of attributes (from attrValues) to retain for ancestor lookup via getAnyParentAttr() / hasAnyParentAttr(), even after this node is no longer the current node. See Ancestor Attributes (keep).
Example:
matcher.push("user", { id: "123", type: "admin" });matcher.push("item"); // No attributesmatcher.push("Envelope", null, "soap"); // With namespacematcher.push("Body", { version: "1.1" }, "soap"); // With bothmatcher.push("Body", { version: "1.1" }, "soap", { keep: ["version"] }); // Retain "version" for descendants
Position vs Counter:
Position: The child index in the parent (0, 1, 2, 3...)
Counter: How many times this tag name appeared at this level (0, 1, 2...)
const expr = new Expression("root.users.user");if (matcher.matches(expr)) { // Current path matches}
matchesAny(exprSet) → boolean
Please check ExpressionSet class for more details.
const matcher = new Matcher();const exprSet = new ExpressionSet();exprSet.add(new Expression("root.users.user"));exprSet.add(new Expression("root.config.*"));exprSet.seal();if (matcher.matchesAny(exprSet)) { // Current path matches any expression in the set}
getCurrentTag()
Get current tag name.
const tag = matcher.getCurrentTag(); // "user"
getCurrentNamespace()
Get current namespace.
const ns = matcher.getCurrentNamespace(); // "soap" or undefined
getAttrValue(attrName)
Get attribute value of current node.
const id = matcher.getAttrValue("id"); // "123"
hasAttr(attrName)
Check if current node has an attribute.
if (matcher.hasAttr("id")) { // Current node has "id" attribute}
getAnyParentAttr(attrName)
Get the value of an attribute that was explicitly kept (via push(..., { keep: [...] })) by the current node or any ancestor. Unlike getAttrValue(), this works regardless of how far the path has descended since the attribute was pushed — but only for names that were marked with keep at push time. If the same name was kept at multiple depths, the nearest (most recent) one wins.
matcher.push("Body", { version: "1.1" }, "soap", { keep: ["version"] });matcher.push("GetUserRequest");matcher.push("UserId");matcher.getAttrValue("version"); // undefined — Body is no longer currentmatcher.getAnyParentAttr("version"); // "1.1" — still reachable, because it was kept
hasAnyParentAttr(attrName)
Check whether the current node or any ancestor kept the given attribute via push(..., { keep: [...] }).
if (matcher.hasAnyParentAttr("version")) { // Some node on the path (current or ancestor) kept "version"}
getPosition()
Get sibling position of current node (child index in parent).
const position = matcher.getPosition(); // 0, 1, 2, ...
getCounter()
Get repeat counter of current node (occurrence count of this tag name).
Returns a MatcherView — a lightweight, live read-only view of the matcher. All query and inspection methods work normally and always reflect the current state of the underlying matcher. Mutation methods (push, pop, reset, updateCurrent, restore) simply don't exist on MatcherView, so misuse is caught at compile time by TypeScript rather than at runtime.
The same instance is returned on every call — no allocation occurs per invocation. This is the recommended way to share the matcher with callbacks, plugins, or any external code that only needs to inspect the current path.
const view = matcher.readOnly();// Same reference every time — safe to cacheview === matcher.readOnly(); // true
What works on the view:
view.matches(expr) // ✓ pattern matchingview.getCurrentTag() // ✓ current tag nameview.getCurrentNamespace() // ✓ current namespaceview.getAttrValue("id") // ✓ attribute valueview.hasAttr("id") // ✓ attribute presence checkview.getPosition() // ✓ sibling positionview.getCounter() // ✓ occurrence counterview.getDepth() // ✓ path depthview.toString() // ✓ path as stringview.toArray() // ✓ path as array
What doesn't exist (compile-time error in TypeScript):
view.push("child", {}) // ✗ Property 'push' does not exist on type 'MatcherView'view.pop() // ✗ Property 'pop' does not exist on type 'MatcherView'view.reset() // ✗ Property 'reset' does not exist on type 'MatcherView'view.updateCurrent({}) // ✗ Property 'updateCurrent' does not exist on type 'MatcherView'view.restore(snapshot) // ✗ Property 'restore' does not exist on type 'MatcherView'
The view is live — it always reflects the current state of the underlying matcher.
const matcher = new Matcher();const view = matcher.readOnly();matcher.push("root");view.getDepth(); // 1 — immediately reflects the pushmatcher.push("users");view.getDepth(); // 2 — still live
💡 Usage Examples
Example 1: XML Parser with stopNodes
import { XMLParser } from 'fast-xml-parser';import { Expression, Matcher } from 'path-expression-matcher';class MyParser { constructor() { this.matcher = new Matcher(); // Pre-compile stop node patterns this.stopNodeExpressions = [ new Expression("html.body.script"), new Expression("html.body.style"), new Expression("..svg"), ]; } parseTag(tagName, attrs) { this.matcher.push(tagName, attrs); // Check if this is a stop node for (const expr of this.stopNodeExpressions) { if (this.matcher.matches(expr)) { // Don't parse children, read as raw text return this.readRawContent(); } } // Continue normal parsing this.parseChildren(); this.matcher.pop(); }}
Example 2: Conditional Processing
const matcher = new Matcher();const userExpr = new Expression("..user[type=admin]");const firstItemExpr = new Expression("..item:first");function processTag(tagName, value, attrs) { matcher.push(tagName, attrs); if (matcher.matches(userExpr)) { value = enhanceAdminUser(value); } if (matcher.matches(firstItemExpr)) { value = markAsFirst(value); } matcher.pop(); return value;}
Example 3: Path-based Filtering
const patterns = [ new Expression("data.users.user"), new Expression("data.posts.post"), new Expression("..comment[approved=true]"),];function shouldInclude(matcher) { return patterns.some(expr => matcher.matches(expr));}
Example 4: Custom Separator
const matcher = new Matcher({ separator: '/' });const expr = new Expression("root/config/database", { separator: '/' });matcher.push("root");matcher.push("config");matcher.push("database");console.log(matcher.toString()); // "root/config/database"console.log(matcher.matches(expr)); // true
Example 5: Attribute Checking
const matcher = new Matcher();matcher.push("root");matcher.push("user", { id: "123", type: "admin", status: "active" });// Check attribute existence (current node only)console.log(matcher.hasAttr("id")); // trueconsole.log(matcher.hasAttr("email")); // false// Get attribute value (current node only)console.log(matcher.getAttrValue("type")); // "admin"// Match by attributeconst expr1 = new Expression("user[id]");console.log(matcher.matches(expr1)); // trueconst expr2 = new Expression("user[type=admin]");console.log(matcher.matches(expr2)); // true
getAttrValue() / hasAttr() only ever see the current node — by design, ancestor attribute values are discarded as soon as you push past them, to keep memory usage low. If you know in advance that a specific attribute (e.g. a SOAP envelope's version, or xml:space) will matter much deeper in the tree, mark it to be kept:
const matcher = new Matcher();matcher.push("Envelope", null, "soap");matcher.push("Body", { version: "1.1" }, "soap", { keep: ["version"] });matcher.push("GetUserRequest", { id: "42" });matcher.push("UserId");// Ordinary attribute access only sees the current node:console.log(matcher.getAttrValue("version")); // undefined// getAnyParentAttr/hasAnyParentAttr still see it, however deep we've gone:console.log(matcher.hasAnyParentAttr("version")); // trueconsole.log(matcher.getAnyParentAttr("version")); // "1.1"matcher.pop(); matcher.pop(); matcher.pop(); // back to Envelopeconsole.log(matcher.hasAnyParentAttr("version")); // false — Body (and its kept attrs) was popped
When to use this: only for the small number of attributes you specifically know you'll need many levels deeper — not as a general substitute for getAttrValue(). Each name passed to keep adds a tiny, constant amount of bookkeeping at push() time; lookups scan only the kept-attributes list (typically 0-3 entries), never the full path, so cost does not grow with document depth.
Example 6: Position vs Counter
const matcher = new Matcher();matcher.push("root");// Mixed tags at same levelmatcher.push("item"); // position=0, counter=0 (first item)matcher.pop();matcher.push("div"); // position=1, counter=0 (first div)matcher.pop();matcher.push("item"); // position=2, counter=1 (second item)console.log(matcher.getPosition()); // 2 (third child overall)console.log(matcher.getCounter()); // 1 (second "item" specifically)// :first uses counter, not positionconst expr = new Expression("root.item:first");console.log(matcher.matches(expr)); // false (counter=1, not 0)
Example 8: Passing a Read-Only View to External Consumers
When passing the matcher into callbacks, plugins, or other code you don't control, use readOnly() to get a MatcherView — it can inspect but never mutate parser state.
import { Expression, Matcher } from 'path-expression-matcher';const matcher = new Matcher();const adminExpr = new Expression("..user[type=admin]");function parseTag(tagName, attrs, onTag) { matcher.push(tagName, attrs); // Pass MatcherView — consumer can inspect but not mutate onTag(matcher.readOnly()); matcher.pop();}// Safe consumer — can only readfunction myPlugin(view) { if (view.matches(adminExpr)) { console.log("Admin at path:", view.toString()); console.log("Depth:", view.getDepth()); console.log("ID:", view.getAttrValue("id")); }}// view.push(...) or view.reset() don't exist on MatcherView —// TypeScript catches misuse at compile time.parseTag("user", { id: "1", type: "admin" }, myPlugin);
const matcher = new Matcher();const soapExpr = new Expression("soap::Envelope.soap::Body..ns::UserId");// Parse SOAP documentmatcher.push("Envelope", { xmlns: "..." }, "soap");matcher.push("Body", null, "soap");matcher.push("GetUserRequest", null, "ns");matcher.push("UserId", null, "ns");// Match namespaced patternif (matcher.matches(soapExpr)) { console.log("Found UserId in SOAP body"); console.log(matcher.toString()); // "soap:Envelope.soap:Body.ns:GetUserRequest.ns:UserId"}// Namespace-specific countersmatcher.reset();matcher.push("root");matcher.push("item", null, "ns1"); // ns1::item counter=0matcher.pop();matcher.push("item", null, "ns2"); // ns2::item counter=0 (different namespace)matcher.pop();matcher.push("item", null, "ns1"); // ns1::item counter=1const firstNs1Item = new Expression("root.ns1::item:first");console.log(matcher.matches(firstNs1Item)); // false (counter=1)const secondNs1Item = new Expression("root.ns1::item:nth(1)");console.log(matcher.matches(secondNs1Item)); // true// NO AMBIGUITY: Tags named after position keywordsmatcher.reset();matcher.push("root");matcher.push("first", null, "ns"); // Tag named "first" with namespaceconst expr = new Expression("root.ns::first");console.log(matcher.matches(expr)); // true - matches namespace "ns", tag "first"
🏗️ Architecture
Data Storage Strategy
Ancestor nodes: Store only tag name, position, and counter (minimal memory)
Current node: Store tag name, position, counter, and attribute values
This design minimizes memory usage:
No attribute names stored (derived from values object when needed)
Attribute values only for current node, not ancestors, by default
For 1M nodes with 3 attributes each, saves ~50MB vs storing attribute names
Ancestor Attributes (keep)
The trade-off above is the right default, but XML/SOAP documents occasionally have a handful of attributes — xml:space, a SOAP envelope's version, a feature-flag at the document root — that genuinely need to be visible many levels deeper. Rather than retaining all attribute values for every node (defeating the memory savings above), push() accepts an explicit opt-in:
Only the named attribute(s) are copied into a small side-stack (_keptAttrs), independent of the normal per-node values. Reachable later via getAnyParentAttr(name) / hasAnyParentAttr(name) regardless of depth — see Example 5b.
Why this stays cheap:
Pushing without options costs two extra property reads — no allocation, no measurable overhead (benchmarked: within run-to-run noise vs. plain push()).
Lookups scan only the kept-attributes stack, not the full path — cost is proportional to how many distinct attributes are currently kept (typically 0-3 in real usage), not to document depth.
pop() truncates kept entries belonging to the popped subtree in the same backward-scan style, so the stack never grows unbounded.
The core matches() / _matchSegment pattern-matching path is completely unaffected — keep is a separate, opt-in mechanism with no new expression syntax.
This is intentionally a narrow escape hatch, not a general "remember everything" toggle — overusing keep (e.g. keeping every attribute on every node) reintroduces the same memory cost this library avoids by default.
Matching Strategy
Matching is performed bottom-to-top (from current node toward root):
Start at current node
Match segments from pattern end to start
Attribute expression conditions ([attr=value]) only apply to the current node — ancestors have no attribute data in the path itself. For genuinely ancestor-scoped checks outside of expression matching, use keep (above).
Position selectors use counter (occurrence count), not position (child index)
Performance
Expression parsing: One-time cost when Expression is created
Path tracking: O(1) for push/pop operations (O(k) additionally when options.keep is used, where k = number of kept attribute names — typically 0-3)
Pattern matching: O(n*m) where n = path depth, m = pattern segments
Ancestor attribute lookup: O(k) where k = number of currently-kept attributes, independent of path depth
Memory per ancestor node: ~40-60 bytes (tag, position, counter only)
Memory per current node: ~80-120 bytes (adds attribute values)
🎓 Design Patterns
Pre-compile Patterns (Recommended)
// ✅ GOOD: Parse once, reuse many timesconst expr = new Expression("..user[id]");for (let i = 0; i < 1000; i++) { if (matcher.matches(expr)) { // ... }}
// ❌ BAD: Parse on every iterationfor (let i = 0; i < 1000; i++) { if (matcher.matches(new Expression("..user[id]"))) { // ... }}
Batch Pattern Checking with ExpressionSet (Recommended)
For checking multiple patterns on every tag, use ExpressionSet instead of a manual loop.
It pre-indexes expressions at build time so each call to matchesAny() does an O(1) bucket
lookup rather than a full O(N) scan:
import { Expression, ExpressionSet, Matcher } from 'path-expression-matcher';// Build once at config/startup timeconst stopNodes = new ExpressionSet();stopNodes .add(new Expression('root.users.user')) .add(new Expression('root.config.*')) .add(new Expression('..script')) .seal(); // prevent accidental mutation during parsing// Per-tag — hot pathif (stopNodes.matchesAny(matcher)) { // handle stop node}
This replaces the manual loop pattern:
// ❌ Before — O(N) per tagfunction isStopNode(expressions, matcher) { for (let i = 0; i < expressions.length; i++) { if (matcher.matches(expressions[i])) return true; } return false;}// ✅ After — O(1) lookup per tagconst stopNodes = new ExpressionSet();stopNodes.addAll(expressions);stopNodes.matchesAny(matcher);//or matcher.matchesAny(stopNodes)
📦 ExpressionSet API
ExpressionSet is an indexed collection of Expression objects designed for efficient
bulk matching. Build it once from your config, then call matchesAny() on every tag.
Constructor
const set = new ExpressionSet();
add(expression) → this
Add a single Expression. Duplicate patterns (same pattern string) are silently ignored.
Returns this for chaining. Throws TypeError if the set is sealed.
Prevent further additions. Any subsequent call to add() or addAll() throws a TypeError.
Useful to guard against accidental mutation once parsing has started.
const stopNodes = new ExpressionSet();stopNodes.addAll(patterns).seal();stopNodes.add(new Expression('root.extra')); // ❌ TypeError: ExpressionSet is sealed
size → number
Number of distinct expressions in the set.
set.size; // 3
isSealed → boolean
Whether seal() has been called.
matchesAny(matcher) → boolean
Returns true if the matcher's current path matches any expression in the set.
Accepts both a Matcher instance and a MatcherView.
if (stopNodes.matchesAny(matcher)) { /* ... */ }if (stopNodes.matchesAny(matcher.readOnly())) { /* ... */ } // also works
How indexing works: expressions are bucketed at add() time, not at match time.
Expression type
Bucket
Lookup cost
Fixed path, concrete tag (root.users.user)
depth:tag map
O(1)
Fixed path, wildcard tag (root.config.*)
depth map
O(1)
Deep wildcard (..script)
flat list
O(D) — always scanned
In practice, deep-wildcard expressions are rare in configs, so the list stays small.
findMatch(matcher) → Expression
Returns the Expression instance that matched the current path. Accepts both a Matcher instance and a MatcherView.
const node = stopNodes.findMatch(matcher);
Example 7: ExpressionSet in a real parser loop
import { XMLParser } from 'fast-xml-parser';import { Expression, ExpressionSet, Matcher } from 'path-expression-matcher';// Config-time setupconst stopNodes = new ExpressionSet();stopNodes .addAll(['script', 'style'].map(t => new Expression(`..${t}`))) .seal();const matcher = new Matcher();const parser = new XMLParser({ onOpenTag(tagName, attrs) { matcher.push(tagName, attrs); if (stopNodes.matchesAny(matcher)) { // treat as stop node } }, onCloseTag() { matcher.pop(); },});
🔗 Integration with fast-xml-parser
Basic integration:
import { XMLParser } from 'fast-xml-parser';import { Expression, Matcher } from 'path-expression-matcher';const parser = new XMLParser({ // Custom options using path-expression-matcher stopNodes: ["script", "style"].map(tag => new Expression(`..${tag}`)), tagValueProcessor: (tagName, value, jPath, hasAttrs, isLeaf, matcher) => { // matcher is available in callbacks if (matcher.matches(new Expression("..user[type=admin]"))) { return enhanceValue(value); } return value; }});
📄 License
MIT
🤝 Contributing
Issues and PRs welcome! This package is designed to be used by XML/JSON parsers like fast-xml-parser. But can be used with any formar parser.