我有一系列的XML,其中包含对应的纬度和经度的邮政编码,如下所示;
<?xml version="1.0"?>
<postcodes>
<entry postcode='AB1 0AA' latitude='7.101478' longitude='2.242852' />
<entry postcode='AB1 0AB' latitude='7.201458' longitude='2.122952' />
</postcodes>XML被分割成以某个字母开头的邮政编码,因此在字母表中每个字母都有一个XML。在它们之间,它们拥有英国的所有邮政编码,这意味着最大的这些entry文件中有30万个元素。
我正在循环遍历一个实体对象列表,将它们的post代码通过SAX放入其中,以便根据每个post代码检索longitude和latitude值。因此,如果我有2000个实体对象,我将让SAX运行2000次来检索这些值。下面循环的代码;
em = emf.createEntityManager();
for (Integer id : siteID){
site = em.find(SiteTable.class, id);
if(site != null && site.getPostcode() != null && !site.getPostcode().equals("")){
XMLPositionRetriever.runXMLQuery(site.getPostcode());
}
else{
System.out.println("The site and/or postcode against this Instruction does not exist.");
}
}
em.close();site.getPostcode()成为处理程序中的postcodeToFind。下面使用的唯一方法的代码;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (postcodeToFind.equals(attributes.getValue("postcode"))){
System.out.println("The postcode '"+postcodeToFind+"', has a latitude of "+attributes.getValue("latitude")+" and a longitude of "+attributes.getValue("longitude"));
throw new SAXException();
}
}目前这是耗时的(2000年搜索所需的时间不到4分钟),但我需要加载时间快。最好在30秒以内。到目前为止,我已经设法将负荷时间减少了一半以下;
Q:有人有其他更有效的SAX处理建议吗?
发布于 2013-09-04 12:30:14
如果可以将要检索地理位置的所有邮政编码传递给处理程序,则处理程序可以一次检索它们。这样做的SAXHandler可能如下所示:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXDemo extends DefaultHandler {
private Map<String, Location> postalCodeMap;
static class Location {
String latitude;
String longitude;
}
public SAXDemo(List<String> postalCodes) {
this.postalCodeMap = new HashMap<String, SAXDemo.Location>();
for (String postalCodeToLookFor : postalCodes) {
this.postalCodeMap.put(postalCodeToLookFor, new Location());
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
String postCodeOfElem = attributes.getValue("postcode");
if (postCodeOfElem != null && this.postalCodeMap.containsKey(postCodeOfElem)) {
Location loc = this.postalCodeMap.get(postCodeOfElem);
loc.latitude = attributes.getValue("latitude");
loc.longitude = attributes.getValue("longitude");
}
}
public Location getLocationForPostalCode(String postalCode) {
return this.postalCodeMap.get(postalCode);
}
public Map<String, Location> getAllFoundGeoLocations() {
return this.postalCodeMap;
}
}在这里,您向处理程序的构造函数传递一个String列表,然后让处理程序使用所有XML数据解析文档。解析完成后,可以在postalCodeMap中找到所有检索到的geo位置。
https://stackoverflow.com/questions/18612101
复制相似问题