[英]How to create a handler for parsing a xml using SAX?
I'm using xerces SAX to parse this XML: 我正在使用xerces SAX来解析此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: 因此,我创建了自己的名为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. 现在,从我的spring mvc控制器中,我计划将XML文件作为字符串传递,并且我希望返回一个Product对象。
So inside my ProductSAXHandler I will create my startElement, endElement methods. 因此,在我的ProductSAXHandler中,我将创建startElement,endElement方法。
So should I just create a method that takes the xml as a string, then instantiates this ProductSAXhandler and then call parse? 因此,我是否应该创建一个将xml作为字符串的方法,然后实例化此ProductSAXhandler并调用parse?
This is my first time dealing with xml/sax so I'm a little unclear how to design this class. 这是我第一次处理xml / sax,因此我不清楚如何设计此类。
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. 由于您需要某个
Product
类的实例,该实例可以封装XML中的数据(可能是通过优先选择以结构化的方式),因此最好将JAXB用于此任务。 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. 除非您对将XML输入绑定到对象的自定义有真正特定的要求,否则,这将比使用SAX简单得多。
What you'll need to do is: 您需要做的是:
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. 尽管JAXB需要花一些时间来学习(特别是如果所需的XML-Java映射不是一对一的关系),但从长远来看,我认为您最终将节省时间。
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. 抱歉,如果您确实确实需要SAX,并且此答案不适用,但我认为在使用有些过时的XML处理模型之前,我希望让您知道您的选择。 Note that DOM and StAX might also be of interest to you.
请注意,您可能还对DOM和StAX感兴趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.