diff --git a/src/xslt/xslt.ts b/src/xslt/xslt.ts
index 9b6a090..173c6a9 100644
--- a/src/xslt/xslt.ts
+++ b/src/xslt/xslt.ts
@@ -1332,10 +1332,13 @@ export class Xslt {
// node.transformedNodeName = name;
+ // Fix for Issue 161: Set siblingPosition to preserve document order
+ node.siblingPosition = (output || this.outputDocument).childNodes.length;
+
domAppendChild(output || this.outputDocument, node);
// The element becomes the output node of the source node.
// context.nodeList[context.position].outputNode = node;
- const clonedContext = context.clone(undefined, 0);
+ const clonedContext = context.clone();
await this.xsltChildNodes(clonedContext, template, node);
}
diff --git a/tests/gh_issues_160_161.test.tsx b/tests/gh_issues_160_161.test.tsx
new file mode 100644
index 0000000..66f3917
--- /dev/null
+++ b/tests/gh_issues_160_161.test.tsx
@@ -0,0 +1,74 @@
+/* eslint-disable no-undef */
+import assert from 'assert';
+
+import { Xslt } from '../src/xslt';
+import { XmlParser } from '../src/dom';
+
+describe('Issues 160 and 161', () => {
+
+ // Issue 160
+ it('Issue 160: xsl:element inside for-each should use correct context node', async () => {
+ const xmlString = `
+
+ - Item 1
+ - Item 2
+ `;
+
+ const xsltString = `
+
+
+
+
+
+
+
+
+
+
+ `;
+
+ const expectedOutString = `Item 1
Item 2
`;
+
+ const xsltClass = new Xslt();
+ const xmlParser = new XmlParser();
+ const xml = xmlParser.xmlParse(xmlString);
+ const xslt = xmlParser.xmlParse(xsltString);
+ const outXmlString = await xsltClass.xsltProcess(xml, xslt);
+
+ // Normalize whitespace for comparison if needed, but for now exact match
+ assert.equal(outXmlString.replace(/\s+/g, ''), expectedOutString.replace(/\s+/g, ''));
+ });
+
+ // Issue 161
+ it('Issue 161: Mixing xsl:element and literal tags should preserve order', async () => {
+ const xmlString = `
+
+ - Item 1
+ - Item 2
+ `;
+
+ const xsltString = `
+
+
+
+
+ Gen
+ Lit
+
+
+
+ `;
+
+ // Expected: Interleaved
+ const expectedOutString = `Gen 1Lit 1Gen 2Lit 2`;
+
+ const xsltClass = new Xslt();
+ const xmlParser = new XmlParser();
+ const xml = xmlParser.xmlParse(xmlString);
+ const xslt = xmlParser.xmlParse(xsltString);
+ const outXmlString = await xsltClass.xsltProcess(xml, xslt);
+
+ // console.log('Issue 161 Output:', outXmlString);
+ assert.equal(outXmlString.replace(/\s+/g, ''), expectedOutString.replace(/\s+/g, ''));
+ });
+});