Skip to content

Keep the deduplicated node list of a union - #190

Closed
yxshee wants to merge 1 commit into
antchfx:masterfrom
yxshee:union-dedup
Closed

yxshee wants to merge 1 commit into
antchfx:masterfrom
yxshee:union-dedup

Conversation

@yxshee

@yxshee yxshee commented Nov 9, 2026

Copy link
Copy Markdown

A union returned every node that more than one operand selected once per operand:

doc, _ := xmlquery.Parse(strings.NewReader(`<r><a id="1"/><a id="2"/></r>`))
nav := xmlquery.CreateXPathNavigator(doc)
count := func(e string) int { n := 0; for it := xpath.MustCompile(e).Select(nav); it.MoveNext(); { n++ }; return n }
count("//a | //a")  // 4, expected 2
count(". | .")      // 2, expected 1
count("/r | /*")    // 2, expected 1

libxml2 (xmllint --xpath 'count(//a | //a)') gives 2, 1 and 1: a node-set holds each node once (XPath 1.0 §3.3).

unionQuery.Select already calls sortAndDedupNodes, which sorts the list in document order and compacts the unique nodes to the front, but the returned slice was discarded, so the iterator still walked the full list with the duplicates at its end. The fix keeps the returned slice. The call came in with 38edbc9, and the union tests added in #178 only union disjoint node-sets, which is why they still passed.

Tests: a new TestUnionRemovesDuplicates with nine cases over the employee example (same operand twice, overlapping paths, . | ., /empinfo | /*, three operands, a positional predicate on a union, attributes); all of them except the positional predicate fail without the change (for example //email | //email selects 6 nodes instead of 3). go test ./... passes.

Found by comparing the package with libxml2 on generated expressions.

unionQuery.Select sorted its node list with sortAndDedupNodes but dropped
the returned slice, so the duplicates compacted to the end of the list
were still iterated: //a | //a selected every a twice and . | . selected
the context node twice. Use the returned slice.
@zhengchun

Copy link
Copy Markdown
Contributor

@yxshee ,

Hi, thanks for your PR. The bug has already been fixed in PR #187 (1fdafd5), which was merged recently. Closing this PR accordingly. Appreciate your contribution!

@zhengchun zhengchun closed this Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants