(possibleXml: string)
| 1 | import { DOMParser } from "@xmldom/xmldom"; |
| 2 | |
| 3 | export default function isXML(possibleXml: string): boolean { |
| 4 | let isValid = true; |
| 5 | |
| 6 | // https://www.npmjs.com/package/xmldom |
| 7 | // xmldom handles invalid XML gracefully, so we need to check for errors |
| 8 | // in this way, rather than relying on the return value of parseFromString |
| 9 | // as recommended in this documentation:: |
| 10 | // https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#error_handling |
| 11 | |
| 12 | const xmlDoc = new DOMParser({ |
| 13 | errorHandler: { |
| 14 | warning: () => {}, |
| 15 | error: () => { |
| 16 | isValid = false; |
| 17 | }, |
| 18 | fatalError: () => { |
| 19 | isValid = false; |
| 20 | }, |
| 21 | }, |
| 22 | }).parseFromString(possibleXml, "application/xml"); |
| 23 | |
| 24 | // This line is necessary because xmldom does not throw an error |
| 25 | // if we pass it a plain string. |
| 26 | if (!xmlDoc?.documentElement) isValid = false; |
| 27 | |
| 28 | return isValid; |
| 29 | } |
no outgoing calls
no test coverage detected