简体   繁体   中英

How to create a handler for parsing a xml using SAX?

I'm using xerces SAX to parse this XML:

<product id="123">
  <sku>abc123</sku>
  <location>
    <warehouse>1</warehouse/>
    <level>3</level>
  </location>
  <details>
    <weight unit="kg">150</weight/>
    <mfg>honda</mfg>
  </details>
</product>

So I created my own class named ProductSAXHandler.java:

public class ProductSAXHandler extends DefaultHandler {


}

Now from my spring mvc controller I plan on pass my XML file as a string, and I want a Product object returned.

So inside my ProductSAXHandler I will create my startElement, endElement methods.

So should I just create a method that takes the xml as a string, then instantiates this ProductSAXhandler and then call parse?

This is my first time dealing with xml/sax so I'm a little unclear how to design this class.

This doesn't directly answer your question, but I'm gonna read a bit between the lines and focus on your actual intention...

Since you want an instance of some Product class that encapsulates the data from the XML, probably in a structured way by preference, you'd do much better to use JAXB for this task. Unless you have really specific requirements regarding the customization of binding XML input to objects, this will turn out a lot simpler than using SAX.

What you'll need to do is:

  1. Get a W3C XML Schema for your XML. If you don't have one and can't obtain one, then there are tools out there that can generate a schema based on input XML. Trang makes this very easy.
  2. Generate Java classes from the schema. For this you can use XJC (the XML-to-Java Compiler) available with Sun's JDK. If you're using build tools like Ant or Maven, there's plugins available. This can automate the process to make it part of a full build.
  3. Use the JAXB API with your generated classes to easily turn XML documents into objects and vice-versa.

Although JAXB will take some time to learn (especially if the desired XML-Java mapping isn't 1-to-1), I think you'll end up saving time in the long run.

Sorry if you really do need SAX and this answer is not applicable, but I figured I'd rather let you know your options before using a somewhat archaic XML processing model. Note that DOM and StAX might also be of interest to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM