import * as tXml from '../src/index.js'; import assert from 'node:assert'; import { test } from 'node:test'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; import fs from 'node:fs'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const files = { commented: join(__dirname, 'examples/commented.svg'), commentOnly: join(__dirname, 'examples/commentOnly.svg'), twoComments: join(__dirname, 'examples/twocomments.svg'), tagesschauRSS: join(__dirname, 'examples/tagesschau.rss'), wordpadDocxDocument: join(__dirname, 'examples/wordpad.docx.document.xml'), }; test('tXml is available', () => { assert(tXml, 'tXml should be available'); }); test('empty string returns empty array', () => { assert(Array.isArray(tXml.parse('')), 'tXml should return an empty array for empty string'); }); test('simplest parsing test', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'test', attributes: {}, children: [] }] ); }); test('single attribute', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'test', attributes: { att: 'v' }, children: [] }] ); }); test('multiple attributes', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'test', attributes: { att: 'v', att2: 'two' }, children: [] }] ); }); test('single text node', () => { assert.deepStrictEqual(tXml.parse('childTest'), ['childTest']); }); test('single child text', () => { assert.deepStrictEqual( tXml.parse('childTest'), [{ tagName: 'test', attributes: {}, children: ['childTest'] }] ); }); test('simple closing tag', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'test', attributes: {}, children: [] }] ); }); test('two child nodes', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'test', attributes: {}, children: [ { tagName: 'cc', attributes: {}, children: [] }, { tagName: 'cc', attributes: {}, children: [] } ] }] ); }); test('ignore comments by default', () => { assert.deepStrictEqual( tXml.parse('value'), [{ tagName: 'test', attributes: {}, children: [ { tagName: 'cc', children: [], attributes: { c: 'd' } }, { tagName: 'cc', attributes: {}, children: ['value'] } ] }] ); }); test('ignore doctype declaration', () => { assert.deepStrictEqual( tXml.parse(''), [ '!DOCTYPE html', { tagName: 'test', attributes: {}, children: [ { tagName: 'cc', attributes: {}, children: [] }, { tagName: 'cc', attributes: {}, children: [] } ] } ] ); }); test('filter option', () => { assert.deepStrictEqual( tXml.parse('', { filter: (element) => element.tagName.toLowerCase() === 'cc' }), [ { tagName: 'cc', attributes: {}, children: [] }, { tagName: 'cc', attributes: {}, children: [] } ] ); }); test('simplify', () => { assert.deepStrictEqual( JSON.stringify(tXml.simplify(tXml.parse('onetest3two
'))), JSON.stringify({ test: { cc: ['one', { sub: '3', _attributes: { f: 'test' } }], dd: '' } }) ); }); test('CSS with tag as comment', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'test', attributes: {}, children: [{ tagName: 'style', attributes: {}, children: ['*{some:10px;}/* comment */'] }] }] ); }); test('do not cut off last character in style', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'style', attributes: {}, children: ['p { color: "red" }'] }] ); }); test('JavaScript creating tags in script', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'test', attributes: {}, children: [{ tagName: 'script', attributes: {}, children: ['$("
")'] }] }] ); }); test('stringify keeps optimal XML the same', () => { const x = 'text'; assert.strictEqual(tXml.stringify(tXml.parse(x)), x); }); test('getElementsByClassName', () => { const xShould = [{ tagName: 'h1', attributes: { class: 'test package-name other-class test2' }, children: [] }]; const x = tXml.getElementsByClassName( '

', 'package-name' ); assert.deepStrictEqual(x, xShould); }); test('attribute without value', () => { const s = ''; assert.deepStrictEqual(tXml.stringify(tXml.parse(s)), ''); }); test('stringify can keep explicit closing tags for empty nodes', () => { const s = ''; assert.deepStrictEqual(tXml.stringify(tXml.parse(s), { selfCloseEmpty: false }), s); }); test('stringify preserves parsed self-closing tags when selfCloseEmpty is false', () => { const s = ''; assert.deepStrictEqual( tXml.stringify(tXml.parse(s), { selfCloseEmpty: false }), '' ); }); test('roundtrip preserves mixed empty tag styles when selfCloseEmpty is false', () => { const s = ''; assert.strictEqual(tXml.stringify(tXml.parse(s), { selfCloseEmpty: false }), s); }); test('selfClosed parse flag is non-enumerable for compatibility', () => { const [root] = tXml.parse(''); const child = root.children[0]; assert.strictEqual(typeof child, 'object'); assert.strictEqual(child.selfClosed, true); assert.strictEqual(Object.keys(child).includes('selfClosed'), false); }); test('unquoted attribute value', () => { const s = '

hello mom

'; assert.deepStrictEqual( tXml.parse(s), [{ tagName: 'p', attributes: { type: 'bold' }, children: ['hello mom'] }] ); }); test('unquoted and boolean attributes together', () => { const s = '

hello mom

'; assert.deepStrictEqual( tXml.parse(s), [{ tagName: 'p', attributes: { type: 'bold', disabled: null }, children: ['hello mom'] }] ); }); test('stringify ignores undefined', () => { assert(tXml.stringify(undefined) === ''); }); test('toContentString', () => { assert.strictEqual( tXml.toContentString(tXml.parse('fff')), 'f f f' ); }); test('getElementById', () => { assert.deepStrictEqual( tXml.getElementById('found', 'theId'), { tagName: 'child', attributes: { id: 'theId' }, children: ['found'] } ); }); test('CDATA', () => { assert.deepStrictEqual( tXml.parse(''), [{ tagName: 'xml', attributes: {}, children: ['some data'] }] ); }); test('parse standalone CDATA', () => { assert.deepStrictEqual(tXml.parse(''), ['nothing']); }); test('parse unclosed CDATA', () => { assert.deepStrictEqual(tXml.parse(' { assert.deepStrictEqual( tXml.parse('', { keepComments: true }), [{ tagName: 'test', attributes: {}, children: [''] }] ); }); test('keep two comments', () => { assert.deepStrictEqual( tXml.parse('', { keepComments: true }), [{ tagName: 'test', attributes: {}, children: ['', ''] }] ); }); test('throw on wrong close tag', () => { assert.throws(() => { tXml.parse('robert'); }); }); test('simplifyLostLess empty nodes', () => { assert.deepStrictEqual(tXml.simplifyLostLess([]), {}); }); test('simplifyLostLess string list', () => { assert.deepStrictEqual(tXml.simplifyLostLess(['3']), '3'); }); test('simplifyLostLess ignores non-objects', () => { assert.deepStrictEqual(tXml.simplifyLostLess(['1', 2]), {}); }); test('filter allows nodes without children', () => { assert.deepStrictEqual(tXml.filter([{}], () => true), [{}]); }); test('simplify option with parse', () => { // This should run without error: Issue #24 tXml.parse('TEST', { simplify: true }); assert.ok(true); }); test('parse processing instruction with non-attribute payload', () => { assert.deepStrictEqual( tXml.parse(''), [ { tagName: '?ACE', attributes: {}, children: ['4'] }, { tagName: 'root', attributes: {}, children: [] } ] ); }); test('stringify preserves processing instruction payload', () => { assert.strictEqual( tXml.stringify(tXml.parse('')), '' ); }); test('skipXmlDeclaration option ignores XML declaration', () => { assert.deepStrictEqual( tXml.parse('demo', { skipXmlDeclaration: true }), [{ tagName: 'project', attributes: {}, children: [{ tagName: 'name', attributes: {}, children: ['demo'] }] }] ); }); test('SVG with comment', () => { const svgWithCommentString = fs.readFileSync(files.commented).toString(); assert.deepStrictEqual( tXml.parse(svgWithCommentString), [{ tagName: 'svg', attributes: { height: '200', width: '500' }, children: [{ tagName: 'polyline', attributes: { points: '20,20 40,25 60,40 80,120 120,140 200,180', style: 'fill:none;stroke:black;stroke-width:3' }, children: [] }] }] ); }); test('keepWhitespace option', () => { const wordpadDoc = fs.readFileSync(files.wordpadDocxDocument).toString(); const filtered = tXml.filter( tXml.parse(wordpadDoc, { keepWhitespace: true }), (n) => n.tagName === 'w:t' ); assert.strictEqual(filtered[1].children[0], ' '); }); // ===== ADDITIONAL COMPREHENSIVE TESTS ===== test('parsing arbitrary text/lorem ipsum', () => { const loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'; const result = tXml.parse(loremIpsum); assert.deepStrictEqual(result, [loremIpsum]); assert.strictEqual(result[0], loremIpsum); }); test('parsing mixed text with XML fragments', () => { const mixed = 'Some text before content and after'; const result = tXml.parse(mixed); assert.strictEqual(result.length, 3); assert.strictEqual(result[0], 'Some text before'); assert.deepStrictEqual(result[1], { tagName: 'tag', attributes: {}, children: ['content'] }); assert.strictEqual(result[2], 'and after'); }); test('parsing node with duplicate attribute (last wins)', () => { const result = tXml.parse(''); assert.deepStrictEqual(result, [{ tagName: 'test', attributes: { att: 'third' }, children: [] }]); assert.strictEqual(result[0].attributes.att, 'third', 'last attribute value should win'); }); test('parsing node with many attributes', () => { const manyAttrs = ''; const result = tXml.parse(manyAttrs); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].attributes.id, 'test-id'); assert.strictEqual(result[0].attributes.class, 'test-class another-class'); assert.strictEqual(result[0].attributes['data-value'], '123'); assert.strictEqual(result[0].attributes['data-name'], 'example'); assert.strictEqual(result[0].attributes.style, 'color: red; background: blue;'); assert.strictEqual(result[0].attributes.onclick, 'handleClick()'); assert.strictEqual(result[0].attributes.disabled, null); assert.strictEqual(result[0].attributes['aria-label'], 'Test Label'); assert.strictEqual(result[0].attributes.tabindex, '0'); assert.strictEqual(result[0].attributes.role, 'button'); }); test('parsing example HTML document', () => { const html = ` Test Page

Welcome

This is a test paragraph.

Test Image
© 2025
`; const result = tXml.parse(html); assert(Array.isArray(result)); assert(result.length > 0); // Find the html element const htmlElement = result.find(el => typeof el === 'object' && el.tagName === 'html'); assert(htmlElement, 'html element should exist'); assert.strictEqual(htmlElement.attributes.lang, 'en'); // Check that structure is preserved const head = htmlElement.children.find(el => typeof el === 'object' && el.tagName === 'head'); const body = htmlElement.children.find(el => typeof el === 'object' && el.tagName === 'body'); assert(head, 'head element should exist'); assert(body, 'body element should exist'); }); test('parsing SVG example', () => { const svg = ` Hi `; const result = tXml.parse(svg); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].tagName, 'svg'); assert.strictEqual(result[0].attributes.width, '100'); assert.strictEqual(result[0].attributes.height, '100'); assert.strictEqual(result[0].attributes.xmlns, 'http://www.w3.org/2000/svg'); // Check children const circle = result[0].children.find(el => typeof el === 'object' && el.tagName === 'circle'); const rect = result[0].children.find(el => typeof el === 'object' && el.tagName === 'rect'); const line = result[0].children.find(el => typeof el === 'object' && el.tagName === 'line'); const text = result[0].children.find(el => typeof el === 'object' && el.tagName === 'text'); assert(circle, 'circle should exist'); assert(rect, 'rect should exist'); assert(line, 'line should exist'); assert(text, 'text should exist'); assert.strictEqual(text.children[0], 'Hi'); }); test('parsing RSS feed structure (simple example)', () => { // Use a simpler RSS example - note: link tags need closing tags in RSS const simpleRss = ` Example Feed https://example.com Example description First Item https://example.com/item1 First item description item-1 Second Item https://example.com/item2 Second item description item-2 `; const result = tXml.parse(simpleRss); assert(Array.isArray(result)); // Find the rss element const rss = result.find(el => typeof el === 'object' && el.tagName === 'rss'); assert(rss, 'rss element should exist'); assert.strictEqual(rss.attributes.version, '2.0'); // Find channel const channel = rss.children.find(el => typeof el === 'object' && el.tagName === 'channel'); assert(channel, 'channel element should exist'); // Check for items const items = channel.children.filter(el => typeof el === 'object' && el.tagName === 'item'); assert.strictEqual(items.length, 2, 'should have 2 items'); // Check first item structure const firstItem = items[0]; const title = firstItem.children.find(el => typeof el === 'object' && el.tagName === 'title'); const url = firstItem.children.find(el => typeof el === 'object' && el.tagName === 'url'); assert(title, 'item should have title'); assert(url, 'item should have url'); assert.strictEqual(title.children[0], 'First Item'); }); test('parsing GPX trkpt with time element', () => { const gpx = ` `; const parsed = tXml.parse(gpx); const gpxNode = parsed.find(el => typeof el === 'object' && el.tagName === 'gpx'); assert(gpxNode, 'gpx element should exist'); const trk = gpxNode.children.find(el => typeof el === 'object' && el.tagName === 'trk'); assert(trk, 'trk element should exist'); const trkseg = trk.children.find(el => typeof el === 'object' && el.tagName === 'trkseg'); assert(trkseg, 'trkseg element should exist'); const trkpt = trkseg.children.find(el => typeof el === 'object' && el.tagName === 'trkpt'); assert(trkpt, 'trkpt element should exist'); assert.strictEqual(trkpt.attributes.lat, '48.208174'); assert.strictEqual(trkpt.attributes.lon, '16.373819'); const timeNode = trkpt.children.find(el => typeof el === 'object' && el.tagName === 'time'); assert(timeNode, 'time element should exist inside trkpt'); assert.strictEqual(timeNode.children[0], '2026-05-10T12:34:56Z'); }); test('getElementById performance on large text', () => { // Generate a large XML document const largeDoc = '' + Array.from({ length: 1000 }, (_, i) => `Item ${i}${i * 10}` ).join('') + ''; // Test getElementById (should be faster as it uses regex search) const startGetById = Date.now(); const result = tXml.getElementById(largeDoc, 'item999'); const timeGetById = Date.now() - startGetById; assert(result, 'getElementById should find the element'); assert.strictEqual(result.attributes.id, 'item999'); // Test full parse (should be slower) const startFullParse = Date.now(); const fullParsed = tXml.parse(largeDoc); const timeFullParse = Date.now() - startFullParse; assert(Array.isArray(fullParsed), 'should parse full document'); // getElementById should be faster than full parse assert(timeGetById < timeFullParse, `getElementById (${timeGetById}ms) should be faster than full parse (${timeFullParse}ms)`); }); test('parsing XML with namespaces', () => { const xml = ` Content Regular content `; const result = tXml.parse(xml); assert.strictEqual(result[0].tagName, 'root'); assert.strictEqual(result[0].attributes['xmlns:custom'], 'http://example.com/custom'); const customElement = result[0].children.find(el => typeof el === 'object' && el.tagName === 'custom:element' ); assert(customElement, 'namespaced element should exist'); assert.strictEqual(customElement.attributes['custom:attr'], 'value'); }); test('parsing deeply nested structure', () => { const depth = 50; const openTags = Array.from({ length: depth }, (_, i) => ``).join(''); const closeTags = Array.from({ length: depth }, (_, i) => ``).join(''); const nested = openTags + 'deepest content' + closeTags; const result = tXml.parse(nested); assert.strictEqual(result.length, 1); // Navigate to the deepest level let current = result[0]; for (let i = 1; i < depth; i++) { assert.strictEqual(current.children.length, 1); current = current.children[0]; assert.strictEqual(current.tagName, `level${i}`); } assert.strictEqual(current.children[0], 'deepest content'); }); test('parsing with special characters in attributes', () => { const xml = ` `; const result = tXml.parse(xml); assert.strictEqual(result[0].attributes.attr1, 'value with & ampersand'); assert.strictEqual(result[0].attributes.attr2, 'value with < less than'); assert.strictEqual(result[0].attributes.attr3, 'value with > greater than'); }); test('parse decodeEntities option decodes text and attributes', () => { const xml = 'a < b && c > d'; const [msg] = tXml.parse(xml, { decodeEntities: true }); assert.strictEqual(msg.attributes.a, 'x & y'); assert.strictEqual(msg.attributes.b, '>'); assert.strictEqual(msg.attributes.c, '<'); assert.strictEqual(msg.children[0], 'a < b && c > d'); }); test('parse decodeEntities keeps unknown entities unchanged', () => { const xml = 'a &unknown; b'; const [msg] = tXml.parse(xml, { decodeEntities: true }); assert.strictEqual(msg.attributes.attr, 'x &unknown; y'); assert.strictEqual(msg.children[0], 'a &unknown; b'); }); test('parsing empty and self-closing tags', () => { const xml = ''; const result = tXml.parse(xml); assert.strictEqual(result[0].tagName, 'root'); assert.strictEqual(result[0].children.length, 4); assert.strictEqual(result[0].children[0].selfClosed, undefined); assert.strictEqual(result[0].children[1].selfClosed, true); assert.strictEqual(result[0].children[2].selfClosed, true); assert.strictEqual(result[0].children[3].selfClosed, true); result[0].children.forEach(child => { if (typeof child === 'object') { assert.deepStrictEqual(child.children, []); } }); }); test('parsing with mixed quoted attributes', () => { const xml = ``; const result = tXml.parse(xml); assert.strictEqual(result[0].attributes.single, 'value1'); assert.strictEqual(result[0].attributes.double, 'value2'); assert.strictEqual(result[0].attributes.mixed, 'has "quotes"'); assert.strictEqual(result[0].attributes.other, "has 'quotes'"); }); test('parsing JSON example within XML', () => { const xml = ` {"name": "test", "value": 123, "nested": {"key": "value"}} content `; const result = tXml.parse(xml); const jsonElement = result[0].children.find(el => typeof el === 'object' && el.tagName === 'json'); assert(jsonElement); const jsonContent = jsonElement.children[0]; const parsed = JSON.parse(jsonContent); assert.strictEqual(parsed.name, 'test'); assert.strictEqual(parsed.value, 123); assert.deepStrictEqual(parsed.nested, { key: 'value' }); }); test('parsing XML with processing instructions', () => { const xml = 'content'; const result = tXml.parse(xml); // Processing instructions should be parsed assert(Array.isArray(result)); const root = result.find(el => typeof el === 'object' && el.tagName === 'root'); assert(root, 'root element should exist'); }); test('performance comparison: getElementById vs full parse for large document', () => { // Create a very large document (10000 elements) const elementsCount = 10000; const targetId = 'target-element-9999'; let largeXml = ''; for (let i = 0; i < elementsCount; i++) { const id = i === 9999 ? targetId : `element-${i}`; largeXml += `Content ${i}`; } largeXml += ''; // Measure getElementById const start1 = process.hrtime.bigint(); const foundElement = tXml.getElementById(largeXml, targetId); const end1 = process.hrtime.bigint(); const getByIdTime = Number(end1 - start1) / 1000000; // Convert to milliseconds assert(foundElement, 'getElementById should find element'); assert.strictEqual(foundElement.attributes.id, targetId); // Measure full parse and search const start2 = process.hrtime.bigint(); const parsed = tXml.parse(largeXml); const rootElement = parsed.find(el => typeof el === 'object' && el.tagName === 'root'); const foundInParse = rootElement.children.find(el => typeof el === 'object' && el.attributes.id === targetId ); const end2 = process.hrtime.bigint(); const fullParseTime = Number(end2 - start2) / 1000000; // Convert to milliseconds assert(foundInParse, 'full parse should find element'); // Log performance comparison console.log(`\n Performance comparison for ${elementsCount} elements:`); console.log(` getElementById: ${getByIdTime.toFixed(2)}ms`); console.log(` Full parse: ${fullParseTime.toFixed(2)}ms`); console.log(` Speedup: ${(fullParseTime / getByIdTime).toFixed(2)}x faster`); // getElementById should be significantly faster assert(getByIdTime < fullParseTime, `getElementById should be faster than full parse (${getByIdTime.toFixed(2)}ms vs ${fullParseTime.toFixed(2)}ms)`); }); test('parsing malformed HTML throws on mismatched tags', () => { // tXml correctly throws errors on mismatched closing tags const malformed = '

Unclosed paragraph

Another div
'; // Should throw because

is not properly closed before

assert.throws(() => { tXml.parse(malformed); }, /Unexpected close tag/); }); test('parsing with unicode and emoji', () => { const xml = 'Hello 世界 🌍 🚀 ❤️'; const result = tXml.parse(xml); assert.strictEqual(result[0].tagName, 'message'); assert.strictEqual(result[0].attributes.lang, '多语言'); assert.strictEqual(result[0].children[0], 'Hello 世界 🌍 🚀 ❤️'); }); test('stringify with duplicate attributes preserves last value', () => { const parsed = [{ tagName: 'test', attributes: { id: 'final-value' }, children: [] }]; const result = tXml.stringify(parsed); assert.strictEqual(result, ''); }); test('stringify encodeEntities option encodes text and attributes', () => { const parsed = [{ tagName: 'test', attributes: { attr: 'a < b && c > d "quote" and \'apostrophe\'' }, children: ['x < y && y > z'] }]; const result = tXml.stringify(parsed, { encodeEntities: true }); assert.strictEqual( result, 'x < y && y > z' ); }); test('stringify trims text nodes by default', () => { const parsed = [{ tagName: 'root', attributes: {}, children: [' left ', { tagName: 'b', attributes: {}, children: [' in '] }, ' right '] }]; assert.strictEqual(tXml.stringify(parsed), 'leftinright'); }); test('stringify keepWhitespace preserves text node whitespace', () => { const parsed = [{ tagName: 'root', attributes: {}, children: [' left ', { tagName: 'b', attributes: {}, children: [' in '] }, ' right '] }]; assert.strictEqual( tXml.stringify(parsed, { keepWhitespace: true }), ' left in right ' ); }); test('stringify keepWhitespaces preserves text node whitespace', () => { const parsed = [{ tagName: 'root', attributes: {}, children: [' left ', { tagName: 'b', attributes: {}, children: [' in '] }, ' right '] }]; assert.strictEqual( tXml.stringify(parsed, { keepWhitespaces: true }), ' left in right ' ); }); test('parse keepWhitespace and stringify keepWhitespaces roundtrip text spacing', () => { const xml = ' left in right '; const parsed = tXml.parse(xml, { keepWhitespace: true }); assert.strictEqual(tXml.stringify(parsed, { keepWhitespaces: true }), xml); }); test('parse decodeEntities and stringify encodeEntities roundtrip entities', () => { const xml = '1 < 2 && 3 > 2'; const parsed = tXml.parse(xml, { decodeEntities: true }); const out = tXml.stringify(parsed, { encodeEntities: true }); assert.strictEqual(out, xml); }); test('issue #52: simplify handles valid XML string with declaration', () => { const xml = ` 0 Vígjáték 2024-04-01T23:10:00.000Z A szentfazék `; const fromString = tXml.simplify(xml); const fromParsed = tXml.simplify(tXml.parse(xml)); assert.deepStrictEqual(fromString, fromParsed); assert.strictEqual(fromString.getschedulesforgenchannellist.schedules.account, '0'); assert.strictEqual(fromString.getschedulesforgenchannellist.schedules.schedule.category, 'Vígjáték'); }); test('issue #45: filter option works recursively on parse, distinct from array filter', () => { const xml = ''; // parse option filter: recursive search on all nodes const itemsByParseFilter = tXml.parse(xml, { filter: (node) => node.tagName === 'node' && node.attributes.type === 'item' }); assert.strictEqual(itemsByParseFilter.length, 2); assert.strictEqual(itemsByParseFilter[0].attributes.id, '1'); assert.strictEqual(itemsByParseFilter[1].attributes.id, '3'); // Array.filter on parse result: only filters top-level array (usually root(s)) const itemsByArrayFilter = tXml.parse(xml).filter( (node) => typeof node === 'object' && node.tagName === 'node' ); assert.strictEqual(itemsByArrayFilter.length, 0); // root is not a 'node' tag // getElementById: searches attribute by name (default 'id') const byId = tXml.getElementById(xml, '2'); assert.strictEqual(byId.tagName, 'node'); assert.strictEqual(byId.attributes.id, '2'); }); test('parsing complex SVG with paths and transforms', () => { const complexSvg = ` `; const result = tXml.parse(complexSvg); assert.strictEqual(result[0].tagName, 'svg'); const defs = result[0].children.find(el => typeof el === 'object' && el.tagName === 'defs'); const path = result[0].children.find(el => typeof el === 'object' && el.tagName === 'path'); const g = result[0].children.find(el => typeof el === 'object' && el.tagName === 'g'); assert(defs, 'should have defs element'); assert(path, 'should have path element'); assert(g, 'should have g element'); assert.strictEqual(path.attributes.d, 'M10 10 H 90 V 90 H 10 L 10 10'); assert.strictEqual(g.attributes.transform, 'translate(50,50)'); }); test('parsing MathML example', () => { const mathml = ` x = - b ± b2 - 4ac 2a `; const result = tXml.parse(mathml); assert.strictEqual(result[0].tagName, 'math'); assert.strictEqual(result[0].attributes.xmlns, 'http://www.w3.org/1998/Math/MathML'); const mrow = result[0].children.find(el => typeof el === 'object' && el.tagName === 'mrow'); assert(mrow, 'should have mrow element'); }); test('parsing SOAP envelope example', () => { const soap = ` user123 secret IBM `; const result = tXml.parse(soap); const envelope = result.find(el => typeof el === 'object' && el.tagName === 'soap:Envelope'); assert(envelope, 'should have soap:Envelope'); assert.strictEqual(envelope.attributes['xmlns:soap'], 'http://www.w3.org/2003/05/soap-envelope'); const header = envelope.children.find(el => typeof el === 'object' && el.tagName === 'soap:Header'); const body = envelope.children.find(el => typeof el === 'object' && el.tagName === 'soap:Body'); assert(header, 'should have header'); assert(body, 'should have body'); }); test('parsing HTML5 doctype', () => { const html5 = 'Test

Hello

'; const result = tXml.parse(html5); assert.strictEqual(result[0], '!DOCTYPE html'); const html = result.find(el => typeof el === 'object' && el.tagName === 'html'); assert(html, 'should have html element'); }); test('getElementsByClassName with multiple classes', () => { const html = `
Item 1 Item 2 Item 3 Item 4
`; const highlighted = tXml.getElementsByClassName(html, 'highlight'); assert.strictEqual(highlighted.length, 3); const active = tXml.getElementsByClassName(html, 'active'); assert.strictEqual(active.length, 3); }); test('performance: getElementById vs getElementsByClassName', () => { const largeDoc = '' + Array.from({ length: 5000 }, (_, i) => `Content ${i}` ).join('') + ''; // Test getElementById const start1 = process.hrtime.bigint(); const byId = tXml.getElementById(largeDoc, 'id4999'); const end1 = process.hrtime.bigint(); const idTime = Number(end1 - start1) / 1000000; // Test getElementsByClassName const start2 = process.hrtime.bigint(); const byClass = tXml.getElementsByClassName(largeDoc, 'special-9'); const end2 = process.hrtime.bigint(); const classTime = Number(end2 - start2) / 1000000; assert(byId, 'getElementById should find element'); assert(byClass.length > 0, 'getElementsByClassName should find elements'); console.log(`\n getElementById vs getElementsByClassName:`); console.log(` getElementById: ${idTime.toFixed(2)}ms`); console.log(` getElementsByClassName: ${classTime.toFixed(2)}ms`); }); test('parsing XML with various whitespace handling', () => { const xml = ` text with spaces text with spaces `; const result = tXml.parse(xml); const preserve = result[0].children.find(el => typeof el === 'object' && el.tagName === 'preserve'); const normal = result[0].children.find(el => typeof el === 'object' && el.tagName === 'normal'); assert(preserve); assert(normal); // By default, whitespace is trimmed assert.strictEqual(normal.children[0], 'text with spaces'); }); test('toContentString with nested elements', () => { const xml = '
The Title

First paragraph with bold text and italic.

Second paragraph.

'; const parsed = tXml.parse(xml); const content = tXml.toContentString(parsed); assert(content.includes('The Title')); assert(content.includes('First paragraph')); assert(content.includes('bold text')); assert(content.includes('italic')); assert(content.includes('Second paragraph')); }); test('filter with depth parameter', () => { const xml = 'deep'; const parsed = tXml.parse(xml); let maxDepth = 0; tXml.filter(parsed, (node, index, depth) => { if (depth > maxDepth) maxDepth = depth; return true; }); assert(maxDepth >= 3, `should have depth of at least 3, got ${maxDepth}`); }); test('filter callback receives stable index depth and path values', () => { const xml = ''; const parsed = tXml.parse(xml); const seen = []; tXml.filter(parsed, (node, index, depth, path) => { seen.push({ tagName: node.tagName, index, depth, path }); return false; }); assert.deepStrictEqual(seen, [ { tagName: 'root', index: 0, depth: 0, path: '' }, { tagName: 'a', index: 0, depth: 1, path: '0.root' }, { tagName: 'group', index: 1, depth: 1, path: '0.root' }, { tagName: 'b', index: 0, depth: 2, path: '0.root.1.group' }, { tagName: 'c', index: 1, depth: 2, path: '0.root.1.group' }, { tagName: 'd', index: 2, depth: 1, path: '0.root' } ]); }); test('filter keeps preorder and original node identity', () => { const xml = ''; const parsed = tXml.parse(xml); const root = parsed[0]; const firstItem = root.children[0]; const group = root.children[1]; const secondItem = group.children[0]; const thirdItem = root.children[2]; const items = tXml.filter(parsed, (node) => node.tagName === 'item'); assert.strictEqual(items.length, 3); assert.strictEqual(items[0], firstItem); assert.strictEqual(items[1], secondItem); assert.strictEqual(items[2], thirdItem); }); test('filter respects explicit starting depth and path', () => { const xml = ''; const parsed = tXml.parse(xml); const seen = []; tXml.filter(parsed, (node, index, depth, path) => { seen.push({ tagName: node.tagName, index, depth, path }); return false; }, 5, 'seed.path'); assert.deepStrictEqual(seen, [ { tagName: 'root', index: 0, depth: 5, path: 'seed.path' }, { tagName: 'child', index: 0, depth: 6, path: 'seed.path.0.root' } ]); }); test('simplify with arrays of similar elements', () => { const xml = 'FirstSecondThird'; const parsed = tXml.parse(xml); const simplified = tXml.simplify(parsed); assert(simplified.list); assert(Array.isArray(simplified.list.item)); assert.strictEqual(simplified.list.item.length, 3); assert.strictEqual(simplified.list.item[0], 'First'); assert.strictEqual(simplified.list.item[1], 'Second'); assert.strictEqual(simplified.list.item[2], 'Third'); }); test('parsing with very long attribute values', () => { const longValue = 'a'.repeat(10000); const xml = ``; const result = tXml.parse(xml); assert.strictEqual(result[0].attributes.data.length, 10000); assert.strictEqual(result[0].attributes.data, longValue); }); test('parsing with very long text content', () => { const longText = 'Lorem ipsum '.repeat(1000); const xml = `${longText}`; const result = tXml.parse(xml); assert.strictEqual(result[0].children[0], longText.trim()); }); test('empty attributes and null handling', () => { const xml = ''; const result = tXml.parse(xml); assert.strictEqual(result[0].attributes.required, null); assert.strictEqual(result[0].attributes.disabled, ''); assert.strictEqual(result[0].attributes.empty, ''); assert.strictEqual(result[0].attributes.value, 'actual'); }); test('complex real-world XML: Atom feed', () => { const atom = ` Example Feed 2025-10-21T18:30:02Z John Doe urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 Atom-Powered Robots Run Amok urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2025-10-21T18:30:02Z Some text. `; const result = tXml.parse(atom); const feed = result.find(el => typeof el === 'object' && el.tagName === 'feed'); assert(feed); assert.strictEqual(feed.attributes.xmlns, 'http://www.w3.org/2005/Atom'); const entry = feed.children.find(el => typeof el === 'object' && el.tagName === 'entry'); assert(entry, 'should have entry element'); }); test('selfClosingTags option - link tag behavior', () => { // By default, 'link' is in the selfClosingTags list (like img, br, etc.) const html = 'Test'; const result = tXml.parse(html); const head = result[0]; assert.strictEqual(head.tagName, 'head'); // link should be self-closing const linkTag = head.children.find(el => typeof el === 'object' && el.tagName === 'link'); assert(linkTag, 'should have link element'); assert.strictEqual(linkTag.attributes.rel, 'stylesheet'); assert.deepStrictEqual(linkTag.children, []); }); test('parsing with custom selfClosingTags option', () => { // Test with empty selfClosingTags to allow link to have children const xml = 'content'; const result = tXml.parse(xml, { selfClosingTags: [] }); const container = result[0]; assert.strictEqual(container.tagName, 'container'); const custom = container.children.find(el => typeof el === 'object' && el.tagName === 'custom'); assert(custom); assert.strictEqual(custom.children[0], 'content'); }); test('backward compatibility - noChildNodes still works', () => { // noChildNodes should still work for backward compatibility const xml = 'content'; const result = tXml.parse(xml, { noChildNodes: [] }); const container = result[0]; assert.strictEqual(container.tagName, 'container'); const custom = container.children.find(el => typeof el === 'object' && el.tagName === 'custom'); assert(custom); assert.strictEqual(custom.children[0], 'content'); }); test('isTextNode type guard', () => { const xml = '
Hello World!
'; const [div] = tXml.parse(xml); // Test with text nodes assert.strictEqual(tXml.isTextNode('Hello'), true); assert.strictEqual(tXml.isTextNode(div.children[0]), true); // Test with element nodes assert.strictEqual(tXml.isTextNode(div), false); assert.strictEqual(tXml.isTextNode(div.children[1]), false); // Test filtering const textNodes = div.children.filter(tXml.isTextNode); assert.strictEqual(textNodes.length, 2); assert.strictEqual(textNodes[0], 'Hello'); assert.strictEqual(textNodes[1], '!'); }); test('isElementNode type guard', () => { const xml = '
Hello World!
'; const [div] = tXml.parse(xml); // Test with element nodes assert.strictEqual(tXml.isElementNode(div), true); assert.strictEqual(tXml.isElementNode(div.children[1]), true); // Test with text nodes assert.strictEqual(tXml.isElementNode('Hello'), false); assert.strictEqual(tXml.isElementNode(div.children[0]), false); // Test with null/undefined assert.strictEqual(tXml.isElementNode(null), false); assert.strictEqual(tXml.isElementNode(undefined), false); // Test filtering const elementNodes = div.children.filter(tXml.isElementNode); assert.strictEqual(elementNodes.length, 1); assert.strictEqual(elementNodes[0].tagName, 'span'); }); test('type guards usage in real scenario', () => { const xml = '
TitleText content

Paragraph

More text
'; const [article] = tXml.parse(xml); // Separate text and elements const texts = article.children.filter(tXml.isTextNode); const elements = article.children.filter(tXml.isElementNode); assert.strictEqual(texts.length, 2); assert.strictEqual(elements.length, 2); assert.strictEqual(texts[0], 'Text content'); assert.strictEqual(texts[1], 'More text'); assert.strictEqual(elements[0].tagName, 'title'); assert.strictEqual(elements[1].tagName, 'p'); }); test('attribute values: null vs empty string vs value', () => { // Test the three types of attribute values const xml = ''; const [input] = tXml.parse(xml); // Attribute without value (boolean attribute) assert.strictEqual(input.attributes.disabled, null); assert.strictEqual(input.attributes.checked, null); // Attribute with empty value assert.strictEqual(input.attributes.required, ''); // Attribute with value assert.strictEqual(input.attributes.value, 'test'); // Verify all are present assert(Object.keys(input.attributes).includes('disabled')); assert(Object.keys(input.attributes).includes('required')); assert(Object.keys(input.attributes).includes('value')); assert(Object.keys(input.attributes).includes('checked')); });