Simple XML Validator - The Coding Shala

Home >> Programming Questions >> XML Validator

 In this post, we will are going to implement a Simple XML Validator in the Java language.

Simple XML Validator in Java

The input is an ASCII string, we have to write a Java program to check if the given String is valid XML or not. For simplicity purposes, the XML string only has content and tags.

 The output should be a String for whether the text is valid XML or not. If the XML is invalid, output one of the three error strings:
1. "missing closing tag for <start_tag>"
2. "encountered closing tag without matching open tag for </end tag>"
3. "parse error"

Example 1:
Input: <a>some text</a>
Output: valid

Example 2:
Input: <a>
Output: missing closing tag for <a>

Approach
We can use the stack data structure.

Java Program:

class Solution {
	
	public String validate_xml(String xml) {
		
		if(xml == null || xml.isEmpty()) return "valid";
		
		Stack<String> stack = new Stack<>();
		int i = 0;
		while(i < xml.length()) {
			if(xml.charAt(i) == '<') {
				if(i < xml.length() && xml.charAt(i+1) == '/') {
					//closing tag
					i = i+2;
					StringBuilder end = new StringBuilder("<");
					while(xml.charAt(i) != '>') {
						if(xml.charAt(i) == '<') return "parse error";
						end.append(xml.charAt(i));
						i++;
					}
					if(end.length() == 1) return "parse error";
					end.append(">");
					if(stack.peek().equals(end.toString())) {
						stack.pop();
					} else {
						StringBuilder tag = new StringBuilder("</");
						for(int j=1; j<end.length(); j++) {
							tag.append(end.charAt(j));
						}
						return "encountered closing tag without matching open tag for " + tag.toString();
					}
				} else {
					//start tag
					i++;
					StringBuilder sb = new StringBuilder("<");
					while(xml.charAt(i) != '>') {
						if(xml.charAt(i) == '<') return "parse error";
						sb.append(xml.charAt(i));
						i++;
					}
					if(sb.length() == 1) return "parse error";
					sb.append(">");
					stack.push(sb.toString());
				}
			}
			i++;
		}
		
		if(!stack.isEmpty()) {
			return "missing closing tag for " + stack.pop();
		}
		
		return "valid";
	}
	
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Single Number 2 LeetCode Solution - The Coding Shala