diff --git a/src/dom/html-entity-decoder.ts b/src/dom/html-entity-decoder.ts
index f876651..7511db3 100644
--- a/src/dom/html-entity-decoder.ts
+++ b/src/dom/html-entity-decoder.ts
@@ -38,33 +38,16 @@ export function htmlEntityDecode(text: string): string {
return text;
}
- // Replace named entities
- let result = text.replace(/&([a-zA-Z]+);/g, (match: string, entity: string) => {
- const lower = entity.toLowerCase();
- return NAMED_ENTITIES[lower] || match;
- });
-
- // Replace decimal numeric entities: {
- result = result.replace(/(\d+);/g, (match: string, code: string) => {
- try {
- const num = parseInt(code, 10);
- return String.fromCharCode(num);
- } catch {
- return match;
- }
- });
-
- // Replace hexadecimal numeric entities: « or «
- result = result.replace(/[xX]([0-9a-fA-F]+);/g, (match: string, code: string) => {
- try {
- const num = parseInt(code, 16);
- return String.fromCharCode(num);
- } catch {
- return match;
+ // Decode in a single pass, so the output of one reference (e.g. the "&" from "&")
+ // is never re-read as the start of another one.
+ return text.replace(
+ /&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|([a-zA-Z]+));/g,
+ (match: string, decimal?: string, hex?: string, entity?: string) => {
+ if (decimal) return String.fromCharCode(parseInt(decimal, 10));
+ if (hex) return String.fromCharCode(parseInt(hex, 16));
+ return NAMED_ENTITIES[entity!.toLowerCase()] || match;
}
- });
-
- return result;
+ );
}
/**
diff --git a/src/dom/xml-functions.ts b/src/dom/xml-functions.ts
index 8888457..a1acaad 100644
--- a/src/dom/xml-functions.ts
+++ b/src/dom/xml-functions.ts
@@ -230,6 +230,15 @@ function xmlIsIndentEligibleOutputMethod(options: XmlOutputOptions): boolean {
return options.outputMethod === 'xml' || options.outputMethod === 'xhtml' || options.outputMethod === 'html';
}
+/**
+ * Whether a text value only contains XML whitespace (#x9, #xA, #xD and #x20).
+ * `String.prototype.trim()` can't be used for this: it also strips characters XML treats as
+ * content, such as the non-breaking space (U+00A0).
+ */
+function isXmlWhitespaceOnly(text: string): boolean {
+ return !/[^\t\n\r ]/.test(text);
+}
+
/**
* Whether a node contributes no output to the serialized result. This mirrors
* the skip condition applied to text nodes in `xmlTransformedTextRecursive`:
@@ -242,7 +251,7 @@ function xmlProducesNoOutput(node: XNode): boolean {
return false;
}
const isFromXslText = node.fromXslText === true;
- return !(node.nodeValue && (isFromXslText || node.nodeValue.trim() !== ''));
+ return !(node.nodeValue && (isFromXslText || !isXmlWhitespaceOnly(node.nodeValue)));
}
/**
@@ -283,9 +292,9 @@ function xmlTransformedTextRecursive(node: XNode, buffer: string[], options: Xml
// For text nodes created by xsl:text, don't trim whitespace
// For other text nodes, skip whitespace-only ones
const isFromXslText = node.fromXslText === true;
- if (node.nodeValue && (isFromXslText || node.nodeValue.trim() !== '')) {
+ if (node.nodeValue && (isFromXslText || !isXmlWhitespaceOnly(node.nodeValue))) {
const finalText =
- node.escape && options.escape ? xmlEscapeText(node.nodeValue): xmlUnescapeText(node.nodeValue);
+ node.escape && options.escape ? xmlEscapeText(node.nodeValue) : node.nodeValue;
buffer.push(finalText);
}
} else if (nodeType === DOM_CDATA_SECTION_NODE) {
@@ -495,16 +504,6 @@ function xmlFullNodeName(node: XNode): string {
return nodeName;
}
-/**
- * Replaces HTML/XML entities to their literal characters.
- * Currently implementing only tag delimiters.
- * @param text The text to be transformed.
- * @returns The unescaped text.
- */
-export function xmlUnescapeText(text: string): string {
- return `${text}`.replace(/</g, '<').replace(/>/g, '>');
-}
-
/**
* Escape XML special markup characters: tag delimiter <, >, and entity
* reference start delimiter &. The escaped string can be used in XML
diff --git a/tests/entities-and-nbsp-output.test.tsx b/tests/entities-and-nbsp-output.test.tsx
new file mode 100644
index 0000000..a1ab398
--- /dev/null
+++ b/tests/entities-and-nbsp-output.test.tsx
@@ -0,0 +1,60 @@
+import { XmlParser } from '../src/dom';
+import { Xslt } from '../src/xslt';
+
+const NBSP = ' ';
+
+const transform = async (xml: string, body: string): Promise => {
+ const parser = new XmlParser();
+ const stylesheet = `
+
+ ${body}
+ `;
+ return new Xslt({ outputMethod: 'text' }).xsltProcess(parser.xmlParse(xml), parser.xmlParse(stylesheet));
+};
+
+describe('NBSP-only values', () => {
+ it.each([
+ ['one NBSP', NBSP],
+ ['several NBSP', `${NBSP}${NBSP}`],
+ ['NBSP around a space', `${NBSP} ${NBSP}`]
+ ])('keeps an attribute with %s', async (_name, value) => {
+ const output = await transform(``, '[]');
+ expect(output).toBe(`[${value}]`);
+ });
+
+ it('keeps an element with only NBSP', async () => {
+ const output = await transform(`${NBSP}`, '[]');
+ expect(output).toBe(`[${NBSP}]`);
+ });
+
+ it('still drops whitespace-only text nodes', async () => {
+ const output = await transform(' \n\t ', '[]');
+ expect(output).toBe('[]');
+ });
+});
+
+describe('Entity decoding', () => {
+ it.each([
+ ['%', '%'],
+ ['A', 'A'],
+ ['<', '<'],
+ ['>', '>'],
+ ['&', '&']
+ ])('decodes %s only once', async (source, expected) => {
+ const fromElement = await transform(`a${source}b`, '');
+ const fromAttribute = await transform(``, '');
+ expect(fromElement).toBe(`a${expected}b`);
+ expect(fromAttribute).toBe(`a${expected}b`);
+ });
+
+ it.each([
+ ['%', '%'],
+ ['%', '%'],
+ ['<', '<'],
+ ['>', '>'],
+ ['&', '&']
+ ])('still decodes a real %s reference', async (source, expected) => {
+ const output = await transform(`a${source}b`, '');
+ expect(output).toBe(`a${expected}b`);
+ });
+});