Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ulti;
- import java.util.Stack;
- public class Main
- {
- public static void main(String[] args)
- {
- Stack<String> stack = new Stack<String>();
- String xml = "<foo> some <bar> useless </bar> data </foo>";
- int openStart = xml.indexOf("<"); //find initial start/end values
- int closeStart = xml.indexOf("</");
- int end = xml.indexOf(">");
- while(end != -1) //while end is found
- {
- String tag;
- if(openStart < closeStart) //if "<" comes before "</"
- {
- tag = xml.substring(openStart + 1, end); //push the string onto the stack
- System.out.println("Pushing: " + tag);
- stack.push(tag);
- }
- else //otherwise
- {
- tag = xml.substring(closeStart + 2, end);
- if(stack.peek().equals(tag)) //check to see that the stack's top string equals the closing tag
- {
- System.out.println("Popping: " + tag); //and pop the string
- stack.pop();
- }
- else
- {
- System.out.println("XML Invalid."); //otherwise, xml is invalid
- return;
- }
- }
- xml = xml.substring(end + 1);
- openStart = xml.indexOf("<");
- closeStart = xml.indexOf("</");
- end = xml.indexOf(">");
- }
- if(!stack.isEmpty()) //if anything's left on the stack, then xml is invalid
- {
- System.out.println("XML Invalid.");
- return;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement