Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for XML errors using JavaScript

Tags:

Question: How do I syntax-check my XML in modern browsers (anything but IE)?

I've seen a page on W3Schools which includes an XML syntax-checker. I don't know how it works, but I'd like to know how I may achieve the same behavior.

I've already performed many searches on the matter (with no success), and I've tried using the DOM Parser to check if my XML is "well-formed" (also with no success).

 var xml = 'Caleb'; var parser = new DOMParser(); var doc = parser.parseFromString(xml, 'text/xml'); 

I expect the parser to tell me I have an XML syntax error (i.e. an unclosed name tag). However, it always returns an XML DOM object, as if there were no errors at all.

To summarize, I would like to know how I can automatically check the syntax of an XML document using JavaScript.

P.S. Is there any way I can validate an XML document against a DTD (using JS, and not IE)?

like image 596
caleb531 Avatar asked Jun 13 '11 17:06

caleb531


People also ask

How do I check XML errors?

To install the XML tools plugin, download the plugin zip file, and extract the contents to where you have installed Notepad++ (such as C:\Program Files\Notepad++). Then restart Notepad++, open the XML file you wish to check, click on the "Plugins" menu at the top, select "XML Tools" and click on "Check XML syntax now."

Where can I find XML parsing error?

If the XML parser detects an error in the XML document during parsing, message RNX0351 will be issued. From the message, you can get the specific error code associated with the error, as well as the offset in the document where the error was discovered.

Does JavaScript work with XML?

XML parsing in JavaScript is defined as it is one kind of package or library of the software which provides an interface for the client applications to work with an XML document and it is used in JavaScript to transform the XML document into readable form, nowadays in many browsers, the XML parser is already available ...


2 Answers

Edit: Here is a more concise example, from MDN:

var xmlString = '<a id="a"><b id="b">hey!</b></a>'; var domParser = new DOMParser(); var dom = domParser.parseFromString(xmlString, 'text/xml');  // print the name of the root element or error message dump(dom.documentElement.nodeName == 'parsererror' ? 'error while parsing' : dom.documentElement.nodeName); 
like image 114
NoBugs Avatar answered Oct 03 '22 22:10

NoBugs


NoBugs answer above did not work with a current chrome for me. I suggest:

var sMyString = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>"; var oParser = new DOMParser(); var oDOM = oParser.parseFromString(sMyString, "text/xml"); dump(oDOM.getElementsByTagName('parsererror').length ?       (new XMLSerializer()).serializeToString(oDOM) : "all good"     ); 
like image 26
Henryk Gerlach Avatar answered Oct 03 '22 22:10

Henryk Gerlach