Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 9 additions & 26 deletions src/dom/html-entity-decoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
);
}

/**
Expand Down
25 changes: 12 additions & 13 deletions src/dom/xml-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand All @@ -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)));
}

/**
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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(/&lt;/g, '<').replace(/&gt;/g, '>');
}

/**
* Escape XML special markup characters: tag delimiter <, >, and entity
* reference start delimiter &. The escaped string can be used in XML
Expand Down
60 changes: 60 additions & 0 deletions tests/entities-and-nbsp-output.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { XmlParser } from '../src/dom';
import { Xslt } from '../src/xslt';

const NBSP = ' ';

const transform = async (xml: string, body: string): Promise<string> => {
const parser = new XmlParser();
const stylesheet = `<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">${body}</xsl:template>
</xsl:stylesheet>`;
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(`<r a="${value}"/>`, '[<xsl:value-of select="r/@a"/>]');
expect(output).toBe(`[${value}]`);
});

it('keeps an element with only NBSP', async () => {
const output = await transform(`<r><t>${NBSP}</t></r>`, '[<xsl:value-of select="r/t"/>]');
expect(output).toBe(`[${NBSP}]`);
});

it('still drops whitespace-only text nodes', async () => {
const output = await transform('<r> \n\t </r>', '[<xsl:value-of select="normalize-space(r)"/>]');
expect(output).toBe('[]');
});
});

describe('Entity decoding', () => {
it.each([
['&amp;#37;', '&#37;'],
['&amp;#x41;', '&#x41;'],
['&amp;lt;', '&lt;'],
['&amp;gt;', '&gt;'],
['&amp;amp;', '&amp;']
])('decodes %s only once', async (source, expected) => {
const fromElement = await transform(`<r><t>a${source}b</t></r>`, '<xsl:value-of select="r/t"/>');
const fromAttribute = await transform(`<r a="a${source}b"/>`, '<xsl:value-of select="r/@a"/>');
expect(fromElement).toBe(`a${expected}b`);
expect(fromAttribute).toBe(`a${expected}b`);
});

it.each([
['&#37;', '%'],
['&#x25;', '%'],
['&lt;', '<'],
['&gt;', '>'],
['&amp;', '&']
])('still decodes a real %s reference', async (source, expected) => {
const output = await transform(`<r><t>a${source}b</t></r>`, '<xsl:value-of select="r/t"/>');
expect(output).toBe(`a${expected}b`);
});
});
Loading