以下块会给你YYYY或YYYY/MM或根据您的XML是什么样子YYYY/MM/DD的格式,它处理一些错误情况。然后,您可以转向并将其格式化为java.util.Date对象或任何您想要使用的对象。
在实施任何SAX过滤/处理时,请务必记住,您应该始终对任何拦截的事件调用“超级”,以确保您将事件传递给任何下游处理程序,否则它们将从流中消失,有人在某个时候会遇到一些麻烦。
StringBuilder buf = null;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("month".equals(localName) || "day".equals(localName)) {
if (buf != null) {
buf.append("/");
} else {
throw new SAXException("something went wrong, we received a month and day outside a start-date");
}
} else if ("start-date".equals(localName)){
//there's another error condition that should be handled here if we encounter a start-date but we're already buffering
buf = new StringBuilder();
}
super.startElement(uri,localName,qName);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("start-date".equals(localName)) {
//buf will be int he format of YYYY OR YYYY/MM OR YYYY/MM/DD depending on what was in your XML.
doSomethingWith(buf.toString());
}
super.endElement(uri,localName,qName);
}
@Override
public void characters(char chars[], int start, int length)
throws SAXException {
if (buf != null) {
buf.append(chars, start, length);
}
super.characters(chars,start,length);
}
您可以添加限制,只允许合理的值(例如1-12为月份,1-31为日期,+整数为年份),但您无法处理闰年或年禾/ 31天。 – duffymo
@PeterJaloveczki你到底在问什么?通过“Java日期”你是指一个java.util.Date对象?如果month + day是可选的,那么我不会看到你如何期望从一年内创建像j.u.Date这样的日期时间对象。 –