2

Is there any way to check if a string entered is XML or not?

function fetchData () {
    if (xmlString.value !== "") {   
        parser = new DOMParser;
        xmlDoc = parser.parseFromString(xmlString.value, 'text/xml');
    } else {
        outputHtml.value = "Please type your XML properly";
    }
}

Now I can only check if input is empty.

A.New
  • 97
  • 2
  • 7
  • that so called duplicate question makes the assumption (in the question) that the string is valid XML. This question asks how to check if the string is valid XML. – Jaromanda X Nov 25 '16 at 23:38
  • wrap the `xmlDoc = parseFromString...` code in a try/catch – Jaromanda X Nov 25 '16 at 23:39
  • @JaromandaX Yes, I've also noted this on comments, but it answers it anyway. It's broad to write a XML parser to check if the string is valid XML. –  Nov 25 '16 at 23:40
  • @FREEZE - not one of the answers in the so called duplicate check to see if the input is valid XML, they all rely on the parser throwing an error in the case of invalid input - simple as using `try/catch` – Jaromanda X Nov 25 '16 at 23:44
  • `if (xmlDoc.querySelector('parsererror')) { // error } else { // valid }` – Elad Nov 29 '18 at 20:35

0 Answers0