Created
August 30, 2019 17:35
-
-
Save sz332/91333eae0f4da40110a74c0d6d4dbd05 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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