-3

How can I make sure XML is well formed? Tags are properly nested and the XML is orderly.

Caveat: No helper functions, implement the function that validate the XML is correct.

Example:

  <person>> //extra closing tags 
      <sex>>female</se>x>
      <firstname>Amy</firstname>
      <lastnam>e>Smith</lastnam>e>
  </person>>

I tried implementing stack to solve this problem after researching some solutions but that implementation would fail if there are the same number of right and left tags - as the example above.

Although there are equal number of left and right tags when they're being retrieved from the stack the XML is incorrect, meaning the tags are in the wrong place.

Iyer
  • 3
  • 6
  • 1
    Just throw it into any (sane) XML parser... – Jeff Mercado Jul 30 '14 at 03:48
  • Please specify which language you are working in (and tag your question appropriately) so that other users can help you. – t j Jul 30 '14 at 03:48
  • @Jeff Mercado: The goal here is to implement the XML parser/Serialize validation code. – Iyer Jul 30 '14 at 05:09
  • Why not peek the stack and see if you're going to be adding a duplicate `<` or `>`? If you are, it's invalid. I can't immediately think of a way where they shouldn't alternate. – Marc Baumbach Jul 30 '14 at 12:34

2 Answers2

1

IMHO, unless you have special requirements, do not try to re-invent the wheel. There are many xml parsers around than will choke if xml is incorrect. And if you want later to be able to validate a xml file against a schema, some can do it.

So as suggested by Jeff Mercado simply use a xml parser.

You can just google C++ xml parsers to find all you need, but I do like the presentation of this other post of SO What XML parser should I use in C++?

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Thanks for the suggestion. This is one of the interview questions i was asked recently so i am trying to find answer to this. – Iyer Jul 30 '14 at 06:04
-2

I think that you are right, you must use the stack method to do than, but for your mentioned example:

you should count numbers of "<" and ">" to be equal before running your code.

if number of "<" is not equal to number of ">" means Xml content is not valid

Mohammad Golahi
  • 367
  • 3
  • 8