How to properly parse XML with SAX?

后端 未结 6 1005
梦谈多话
梦谈多话 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条回答
  • 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.

    0 讨论(0)
  • 2020-12-30 16:02

    I usually put objects on a stack, and push/pop them while parsing the XML file (particularly useful if objects are nested, but that's not your case).

    If you want a simpler approach, you need at a pointer to the current ConnectionList and to the current Connection. Since you already know the structure of your file, this could be easier than using a stack-based parser.

    0 讨论(0)
  • 2020-12-30 16:14

    SAX parsers are a bit like looking at a large picture through a tiny spy hole.

    The callback will present you with a single piece of the XML structure at a time. It wont give you any clues as to where you are in the document only a single piece of data is presented,. The element name, the attribute name/value or the text contents.

    Your program needs to track where you are in the document. If you are parsing on the fly a simple stack structure will do -- you push the name onto the stack when you get a "beginelement" and you pop the stack on an "endelement".

    If you find yourself building a tree structure I would switch to a DOM parser as whatever you write will be a pale and buggy shadow of something like XERCES.

    0 讨论(0)
  • 2020-12-30 16:14

    If it's a reasonably small xml document and the memory/throughput constraints aren't prohibitive to an in memory solution, then you could use JAXB instead. You can generate the required classes from the XSD and simply unmarshall the xml into java objects. If you must use a streaming parser, then consider using StAX instead, I generally find this more intuitive.

    0 讨论(0)
  • 2020-12-30 16:27

    Generally speaking you have a couple choices:

    1. Use custom objects to map the XML to, these objects will encapsulate more objects much like the XML elements nest.
    2. Do a generic parsing and traverse the DOM via relative elements.

    To my knowledge there are some tools out there such as JAXB which will generate your classes based on XSD's, but they can sometimes come with a price as generated code often does.

    If you go with option 1 and "roll your own" you'll need to provide methods for unmarshaling and marshaling that go to and from XML and most likely Strings. Something like:

    <Foo>
      <Bar>
        <Baz></Baz>
      </Bar>
      <Thing></Thing>
    </Foo>
    
    // pseudo-code!
    //In Foo.java
    unmarshal( Element element ) {
     unmarshalBar( element );
     unmarshalThing( element );
    }
    
    unmarshalBar( Element element ) {
     //...verify that the element is bar
     bar = new Bar();
     bar.unmarshal( element );
    }
    
    //In Bar.java
    unmarshal( Element element ) {
     unmarshalBaz( element );
    }
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-30 16:28

    The best way I've found (so far) of parsing XML using SAX is to use a stack and conditional statements in the relevant callbacks. Here's an article describing it, and my summary of it:

    The basic premise is that as you parse the document, you create objects to store the parsed data, pushing them onto the stack as you go, peeking at the top of the stack to add data to the current element, and at the end of each element popping it off the stack and storing it in the parent.

    The effect is that you parse the tree of elements depth first, and at the end of each branch you roll it back into the parent until you're left with a single object (such as your ConnectionList) that contains all of the parsed data ready to be used. Essentially, you end up with a series of objects that mirror the structure of the original XML

    That means you need some data objects that can store the data in the same structure as the XML. Complex elements will normally become classes, while simple elements will normally be attributes within classes. The root element is often represented by a list of some kind.

    To start with, you create a stack object to hold the data as you parse it.

    Then, at the start of each element you identify what type it is using localName.equals() method, create an instance of the appropriate class, and push it into the Stack. If the element is a simple element, you will probably model that as an attribute in the class representing the parent element, and you will need a series of flags that tells the parser if such an element is encountered and what element it is so it can be processed in the characters() method.

    The actual data is read using the characters() method, and again you use conditional logic to determine what to do with the data, based on the value of the flag. Essentially, you peek at the top of the stack and use the appropriate method to write the data into the object, converting from text where necessary.

    At the end of each element, you pop the top of the stack and use localName.equals() again to determine how to store it in the object before it (e.g. which setter method needs to be called)

    When you reach the end of the document you should have captured all the data in the document.

    0 讨论(0)
提交回复
热议问题