Validate of XML File and Format
Hi friends. I hope everyone is well. In this article I am trying to make a XML Validation webpage using jQuery or JavaScript. When I am working on a XML file I think I have some good techniques to check whether or not your code is valid. So I decided to create a validattion of XML files using jQuery.
The following is a look at the JavaScript code.
function validateXML(txt) {
var temp = $(txt).val();
if ($(txt).val() !="") {
// code for IE
if (window.ActiveXObject) {
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(document.all(txt).value);
if (xmlDoc.parseError.errorCode != 0) {
txt = "Error Code: " + xmlDoc.parseError.errorCode + "\n";
txt = txt + "Error Reason: " + xmlDoc.parseError.reason;
txt = txt + "Error Line: " + xmlDoc.parseError.line;
alert(txt);
}
else {
alert("No errors found");
}
}
If the text box is empty then the following message shows:
Figure 1.1 Show message if Text box is empty
Just look at the error message above. This message clearly shows that no element was found and shows Line Number 2, Column 1.
If some value is entered that is not well formatted like this:
Just guess what the error message will be. Okay I won't confuse you, check below.
Check the preceding first Row XML parsing error: Syntax error.
It throws an exception. For clarity check the following picture.
Not well formatted
In this example the "<Title>" tag was not closed. So that makes it not properly formatted.
The error message is as in the following:
Case Sensitive error
If the case varies in the data like <title> All is Well </Title>.
Then an exception is fired as in the following:
How to use this script
Find the article attachment. I have attached a complete project. First of all download the attachment and open it in Visula Studi 2010. When complete open the project and check the right side for the Solution Explorer. You will have a jQuery library file and another is ASPX Page. The XML page is named Test_you_xml.aspx. Select this page and click the right mouse button; a dialog box is opened. In this box select to view in a browser.
If everything is right then a message will appear.
Advantage
No waiting any extra time.
Lightweight script.
Real time response.
No downloading of extra software.
Message showing with line number.
Disadvantage
If your browser has JavaScript disabled then it does not work.
Conclusion
This script is very useful when we are creating any type of XML data.
Reference: w3school