Skip to content

Commit

Permalink
fix(xml-builder): xml entity encoding for more characters (#2309)
Browse files Browse the repository at this point in the history
XML entity encoding for carriage return, line feed, next line, line separator characters,
quote and single quote
  • Loading branch information
AllanZhengYP committed Apr 28, 2021
1 parent d52f7e6 commit 96ff164
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
2 changes: 1 addition & 1 deletion packages/xml-builder/src/XmlText.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { XmlText } from "./XmlText";
describe("XmlText", () => {
it("escapes element text", () => {
const text = new XmlText('this & that are < or > "most"');
expect(text.toString()).toBe('this &amp; that are &lt; or &gt; "most"');
expect(text.toString()).toBe("this &amp; that are &lt; or &gt; &quot;most&quot;");
});
});
6 changes: 3 additions & 3 deletions packages/xml-builder/src/escape-element.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { escapeElement } from "./escape-element";

describe("escape-element", () => {
it("escapes: & < >", () => {
const value = 'abc 123 &<>"%';
expect(escapeElement(value)).toBe('abc 123 &amp;&lt;&gt;"%');
it("escapes: & < > \" ' \\n \\r \\u0085 \\u2028", () => {
const value = "abc 123 &<>\"'%\n\r\u0085\u2028";
expect(escapeElement(value)).toBe("abc 123 &amp;&lt;&gt;&quot;&apos;%&#x0A;&#x0D;&#x85;&#x2028;");
});
});
11 changes: 10 additions & 1 deletion packages/xml-builder/src/escape-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,14 @@
* Escapes characters that can not be in an XML element.
*/
export function escapeElement(value: string): string {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
return value
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/\r/g, "&#x0D;")
.replace(/\n/g, "&#x0A;")
.replace(/\u0085/g, "&#x85;")
.replace(/\u2028/, "&#x2028;");
}

0 comments on commit 96ff164

Please sign in to comment.