如何根据XSD定义在SAX上实现策略模式?
like:
if xsd = V1 use V1Parser
if xsd = V2 use V2Parser
if xsd = V3 use V3Parser
else error
问题是我必须查看XML才能知道定义了哪个XSD但是我不能再改变Parser了(我不会再次开始因为xsd不在开头定义/ ERM系统中没有格式良好的XML。)
你知道解决方法吗?
答案 0 :(得分:1)
解决方案可能是使用DefaultHandler VDispatch,它在内部将SAX事件委托给相应的DefaultHandler V1,V2或V3。
在startElement
中,VDispatch查找相关子树的开头。根据子树XSD,它选择相应的处理程序V1,V2或V3。
在子树内部,它会将所有事件转发给所选择的处理程序。
在子树之外,它会忽略所有事件。
public class VDispatch extends DefaultHandler {
private DefaultHandler current_;
private int subtreeLevel_;
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if ((current_ == null) && (subtree-is-starting)) {
current_ = select-handler-based-on-xsd;
subtreeLevel_ = 0;
}
if (current_ != null) {
current_.startElement(uri, localName, qName, attributes);
subtreeLevel_++;
}
}
public void endElement(String uri, String localName, String qName) {
if (current_ != null) {
current_.endElement(uri, localName, qName);
if (--subtreeLevel_ == 0)
current_ = null;
}
}
// simple forwarding in all other DefaultHandler methods
public void characters(char[] ch, int start, int length) {
if (current_ != null)
current_.characters(ch, start, length);
}
}