How to properly parse XML with SAX?

后端 未结 6 1084
梦谈多话
梦谈多话 2020-12-30 15:56

I am receiving an XML document from a REST service which shall be parsed using SAX. Please see the following example which was generated out of the XSD.

Setting up th

6条回答
  •  -上瘾入骨i
    2020-12-30 16:01

    Your SAX event handler should act as a state machine. Your structure is pretty deep, so the state machine will be a bit complex; but this is the basic approach:

    All variables are member variables.

    When you encounter a startElement event, you instantiate an object representing that element then put the object on a stack (or set a flag indicating what value you are working with).

    When you encounter a text event, read the text and set the appropriate value based on the flag you set in the previous step.

    When you encounter a endElement event, you pull the current object off the stack and call the setter on the object that is now on the top of the stack.

    When you exhaust the document, you should only have one object left on the stack which represents everything you've read.

提交回复
热议问题