path-expression-matcher
Efficient path tracking and pattern matching for XML, JSON, YAML or any other parsers.
๐ฏ Purpose
path-expression-matcher provides three core classes for tracking and matching paths:
Expression: Parses and stores pattern expressions (e.g., "root.users.user[id]")
Matcher: Tracks current path during parsing and matches against expressions
MatcherView: A lightweight read-only view of a Matcher, safe to pass to callbacks
Compatible with fast-xml-parser and similar tools.
๐ฆ Installation
npm install path-expression-matcher
๐ Quick Start
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 expression
if (matcher.matches(expr)) {
console.log("Match found!");
console.log("Current path:", matcher.toString()); // "root.users.user"
}
// Namespace support
const 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
๐ง API Reference
Expression
Constructor
new Expression(pattern, options = {}, data)
Parameters:
pattern (string): Pattern to parse
options.separator (string): Path separator (default: '.')
Example:
const expr1 = new Expression("root.users.user");
const expr2 = new Expression("root/users/user", { separator: '/' });
const expr3 = new Expression("root/users/user", { separator: '/' }, { extra: "data"});
console.log(expr3.data) // { extra: "data" }
Methods
hasDeepWildcard() โ boolean
hasAttributeCondition() โ boolean
hasPositionSelector() โ boolean
toString() โ string
Matcher
Constructor
new Matcher(options)
Parameters:
options.separator (string): Default path separator (default: '.')
Path Tracking Methods
push(tagName, attrValues, namespace, options)
Add a tag to the current path. Position and counter are automatically calculated.
Parameters:
tagName (string): Tag name
attrValues (object, optional): Attribute key-value pairs (current node only)
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 attributes
matcher.push("Envelope", null, "soap"); // With namespace
matcher.push("Body", { version: "1.1" }, "soap"); // With both
matcher.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...)
Example:
<root>
<a/> <!-- position=0, counter=0 -->
<b/> <!-- position=1, counter=0 -->
<a/> <!-- position=2, counter=1 -->
</root>
pop()
Remove the last tag from the path.
matcher.pop();
updateCurrent(attrValues)
Update current node's attributes (useful when attributes are parsed after push).
matcher.push("user"); // Don't know values yet
// ... parse attributes ...
matcher.updateCurrent({ id: "123" });
reset()
Clear the entire path.
matcher.reset();
Query Methods
matches(expression)
Check if current path matches an Expression.
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 current
matcher.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).
const counter = matcher.getCounter(); // 0, 1, 2, ...
getIndex() (deprecated)
Alias for getPosition(). Use getPosition() or getCounter() instead for clarity.
const index = matcher.getIndex(); // Same as getPosition()
getDepth()
Get current path depth.
const depth = matcher.getDepth(); // 3 for "root.users.user"
toString(separator?, includeNamespace?)
Get path as string.
Parameters:
separator (string, optional): Path separator (uses default if not provided)
includeNamespace (boolean, optional): Whether to include namespaces (default: true)
const path = matcher.toString(); // "root.ns:user.item"
const path2 = matcher.toString('/'); // "root/ns:user/item"
const path3 = matcher.toString('.', false); // "root.user.item" (no namespaces)
toArray()
Get path as array.
const arr = matcher.toArray(); // ["root", "users", "user"]
State Management
snapshot()
Create a snapshot of current state.
const snapshot = matcher.snapshot();
restore(snapshot)
Restore from a snapshot.
matcher.restore(snapshot);
Read-Only Access
readOnly()
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 cache
view === matcher.readOnly(); // true
What works on the view:
view.matches(expr) // โ pattern matching
view.getCurrentTag() // โ current tag name
view.getCurrentNamespace() // โ current namespace
view.getAttrValue("id") // โ attribute value
view.hasAttr("id") // โ attribute presence check
view.getPosition() // โ sibling position
view.getCounter() // โ occurrence counter
view.getDepth() // โ path depth
view.toString() // โ path as string
view.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.