java sax解析是什么_java – 我应该使用什么模式来使用SAX解析器?

MyObjectA

No

4

Honda

No

我的XML采用这种格式.我正在使用SAX解析器来解析此文件,因为xml文件的大小可能很大.

我应该遵循什么模式来解析文件.

通常我一直在遵循这种方法:

//PseudoCode

if(start){

if(type Office)

{

create an instance of type Office and populate the attributes of Office in the Office class using a call back

}

if(type Vehicle)

{

create an instance of type Vehicle and populate the attributes of Vehicle in the Vehicle class using a call back

}

}

if(end){

// do cleaning up

}

这种方法通常使我的解析函数包含起始和结束标记.

还有其他更好的方法可以遵循.

解决方法:

我对这种方法有很好的经验:

>创建查找表以将节点名称映射到处理程序函数.您很可能需要为每个节点名称维护两个处理程序,一个用于开头,一个用于结束标记.

>维护一组父节点.

>从查找表中调用处理程序.

>每个处理函数都可以执行其任务而无需进一步检查.但是如果需要,每个处理程序也可以通过查看父节点堆栈来确定当前上下文.如果节点层次结构中的不同位置具有相同名称的节点,则这一点很重要.

一些伪Java代码:

public class MyHandler extends DefaultHandler {

private Map startLookup = new HashMap();

private Map endLookup = new HashMap();

private Stack nodeStack = new Stack();

public MyHandler() {

// Initialize the lookup tables

startLookup.put("Office", new MyCallbackAdapter() {

public void execute() { myOfficeStart() }

});

endLookup.put("Office", new MyCallbackAdapter() {

public void execute() { myOfficeEnd() }

});

}

public void startElement(String namespaceURI, String localName,

String qName, Attributes atts) {

nodeStack.push(localName);

MyCallbackAdapter callback = startLookup.get(localName);

if (callback != null)

callback.execute();

}

public void endElement(String namespaceURI, String localName, String qName)

MyCallbackAdapter callback = endLookup.get(localName);

if (callback != null)

callback.execute();

nodeStack.pop();

}

private void myOfficeStart() {

// Do the stuff necessary for the "Office" start tag

}

private void myOfficeEnd() {

// Do the stuff necessary for the "Office" end tag

}

//...

}

一般建议:

根据您的要求,您可能需要更多上下文信息,例如上一个节点名称或当前节点为空.如果您发现自己添加了越来越多的上下文信息,您可能会考虑切换到完整的fletched DOM解析器,除非运行时速度比开发速度更重要.

标签:java,oop,design-patterns

来源: https://codeday.me/bug/20190527/1160125.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值