Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. class Node
  2. def initialize(xml_str)
  3. @name = @attributes = @content = ''
  4. parse(xml_str)
  5. p @name, @attributes, @content
  6. end
  7.  
  8. def parse(xml_str)
  9. # state indicators
  10. inside_tag = inside_tag_name = inside_tag_attributes = false
  11.  
  12. xml_str.each_char do |char|
  13. if char == "<"
  14. if not inside_tag
  15. # state: beginning of tag name
  16. inside_tag = true
  17. inside_tag_name = true
  18. inside_tag_attributes = false
  19. end
  20. elsif char == ">"
  21. if inside_tag
  22. # state: end of tag
  23. inside_tag = false
  24. inside_tag_name = false
  25. inside_tag_attributes = false
  26. end
  27. elsif char == ' '
  28. if inside_tag_name
  29. # state: space between tag name and attribs (or between attribs)
  30. inside_tag_name = false
  31. inside_tag_attributes = true
  32. end
  33. elsif char == '/'
  34. if inside_tag
  35. # state: beginning of closing tag name
  36. inside_tag_name = false
  37. inside_tag_attributes = false
  38. end
  39. else
  40. if inside_tag
  41. if inside_tag_name
  42. # state: reading tag name
  43. @name += char
  44. elsif inside_tag_attributes
  45. # state: reading attributes
  46. @attributes += char
  47. end
  48. else
  49. # state: reading contents
  50. @content += char
  51. end
  52. end
  53. end
  54. end
  55. end
  56.  
  57. string = "<root attrib='value' attrib2=\"value2\">text</root>"
  58. node = Node.new(string)
  59. p node
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement