Advertisement
Guest User

Untitled

a guest
Mar 26th, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. package ulti;
  2.  
  3. import java.util.Stack;
  4.  
  5. public class Main
  6. {
  7. public static void main(String[] args)
  8. {
  9. Stack<String> stack = new Stack<String>();
  10.  
  11. String xml = "<foo> some <bar> useless </bar> data </foo>";
  12.  
  13. int openStart = xml.indexOf("<"); //find initial start/end values
  14. int closeStart = xml.indexOf("</");
  15. int end = xml.indexOf(">");
  16.  
  17. while(end != -1) //while end is found
  18. {
  19. String tag;
  20.  
  21. if(openStart < closeStart) //if "<" comes before "</"
  22. {
  23. tag = xml.substring(openStart + 1, end); //push the string onto the stack
  24. System.out.println("Pushing: " + tag);
  25.  
  26. stack.push(tag);
  27. }
  28. else //otherwise
  29. {
  30. tag = xml.substring(closeStart + 2, end);
  31.  
  32. if(stack.peek().equals(tag)) //check to see that the stack's top string equals the closing tag
  33. {
  34. System.out.println("Popping: " + tag); //and pop the string
  35. stack.pop();
  36. }
  37. else
  38. {
  39. System.out.println("XML Invalid."); //otherwise, xml is invalid
  40.  
  41. return;
  42. }
  43. }
  44.  
  45. xml = xml.substring(end + 1);
  46.  
  47. openStart = xml.indexOf("<");
  48. closeStart = xml.indexOf("</");
  49. end = xml.indexOf(">");
  50. }
  51.  
  52. if(!stack.isEmpty()) //if anything's left on the stack, then xml is invalid
  53. {
  54. System.out.println("XML Invalid.");
  55.  
  56. return;
  57. }
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement