Java 基于 XSD 值的 SAX 策略模式
Java SAX strategy pattern based on XSD value
如何根据 XSD 定义在 SAX 上实现策略模式?
like:
if xsd = V1 use V1Parser
if xsd = V2 use V2Parser
if xsd = V3 use V3Parser
else error
问题是我必须查看 XML 才能知道定义了哪个 XSD 但是我无法再更改解析器(而且我不会重新开始,因为xsd 未在开头定义/格式不正确 XML 来自 ERM 系统)。
您知道解决方法吗?
解决方案可能是使用 DefaultHandler VDispatch,它在内部将 SAX 事件委托给适当的 DefaultHandler V1、V2 或 V3。
In 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);
}
}
如何根据 XSD 定义在 SAX 上实现策略模式?
like:
if xsd = V1 use V1Parser
if xsd = V2 use V2Parser
if xsd = V3 use V3Parser
else error
问题是我必须查看 XML 才能知道定义了哪个 XSD 但是我无法再更改解析器(而且我不会重新开始,因为xsd 未在开头定义/格式不正确 XML 来自 ERM 系统)。
您知道解决方法吗?
解决方案可能是使用 DefaultHandler VDispatch,它在内部将 SAX 事件委托给适当的 DefaultHandler V1、V2 或 V3。
In 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);
}
}