How to properly parse XML with SAX?

后端 未结 6 1117
梦谈多话
梦谈多话 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: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:

    
      
        
      
      
    
    
    // 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.

提交回复
热议问题