0

I'm trying to create a function in C# that will try to automatically generate a closing XML tag when the user types </. Let's say I have following string:

<books>
  <book>
  <author>Tolkien</author>
  <title>Fellowship of the Ring</title>
  </book>
  <book>

When the user types </, this should be directly appended with the string book>.

I am kind of lost on how to find the last unclosed tag (in this case <book> programmatically. Is a regex the best way to do this? Using an XML parser seems to be out of the question since the XML at this point is not valid.

wasmachien
  • 969
  • 1
  • 11
  • 28

1 Answers1

3

Consider using a stack, for every opening tag you push the tag, then whenever you come across '< /' you pop the tag from the stack

<books>
  <book>
  <author>Tolkien</author>
  <title>Fellowship of the Ring</title>
  </book>
  <book>

push books, push book, push author, pop author, push title, pop title, pop book, etc.

at the end of this, whatever is on the stack has not been properly closed

Giel
  • 397
  • 1
  • 9
  • Of course, if you allow editing or deletion of text that has already been typed (and who doesn't?) then it gets rather more complicated. – Michael Kay Sep 24 '17 at 15:35