Skip to content

Instantly share code, notes, and snippets.

@sz332
Created August 30, 2019 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sz332/91333eae0f4da40110a74c0d6d4dbd05 to your computer and use it in GitHub Desktop.
Save sz332/91333eae0f4da40110a74c0d6d4dbd05 to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class XmlValidator {
public boolean isValid(String xml) {
Stack<String> stack = new Stack<>();
boolean opening = false;
boolean closing = false;
String currentTag = "";
for (char c : xml.toCharArray()) {
if (c == '<') {
if (opening == true) {
return false;
}
opening = true;
} else if (c == '/') {
if (closing == true) {
return false;
}
closing = true;
} else if (c == '>') {
if (!closing) {
stack.push(currentTag);
} else {
if (stack.isEmpty()) {
return false;
}
String lastTag = stack.pop();
if (!currentTag.equals(lastTag)) {
return false;
}
}
currentTag = "";
opening = false;
closing = false;
} else {
currentTag += c;
}
}
return stack.isEmpty();
}
}
public class XmlValidatorTest {
XmlValidator validator = new XmlValidator();
@Test
public void testNormal() {
Assert.assertTrue(validator.isValid("<a></a>"));
}
@Test
public void testTwo() {
Assert.assertTrue(validator.isValid("<a></a><b></b>"));
}
@Test
public void testEmbedded() {
Assert.assertTrue(validator.isValid("<a><b></b></a>"));
}
@Test
public void testTwoEmbedded() {
Assert.assertTrue(validator.isValid("<a><b><c></c><d></d></b></a>"));
}
@Test
public void testInvalid0() {
Assert.assertFalse(validator.isValid("<a><"));
}
@Test
public void testInvalid1() {
Assert.assertFalse(validator.isValid("<a>"));
}
@Test
public void testInvalid2() {
Assert.assertFalse(validator.isValid("<a></"));
}
@Test
public void testInvalid3() {
Assert.assertFalse(validator.isValid("<a></a"));
}
@Test
public void testInvalid4() {
Assert.assertFalse(validator.isValid("<a></b>"));
}
@Test
public void testInvalid5() {
Assert.assertFalse(validator.isValid("<a><b></a>"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment