1

我有 7,464 个siteID整数存储在List同名 ( siteID) 中。我正在遍历列表并使用每个siteID整数来查询一个 SQL 表,JPA以返回一个SiteTable实例并获取它的postcode字符串。

然后,我使用这些postcode字符串来检查 XML 文件以检索每个postcode. 下面是循环;

for (Integer id : siteID){           
                siteTable = em.find(SiteTable.class, id);
                XMLPositionRetriever.runXMLQuery(siteTable.getPostcode());         
        }

然后将该邮政编码字符串放入runXMLQuery(String toFind)下面类的方法中;

public class XMLPositionRetriever extends DefaultHandler{

String postcodeToFind;
boolean found = false;

public XMLPositionRetriever(){
}

public XMLPositionRetriever(String toFind){
    postcodeToFind = toFind;
}

public static void runXMLQuery(String toFind){

    try {      
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser(); 
        XMLPositionRetriever handler = new XMLPositionRetriever(toFind);
        saxParser.parse("src\\haldata\\postcodes"+toFind.charAt(0)+".xml", handler);
    }
    catch(Exception e){
        System.out.println(e);
    }

}

@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"));
        found = true;
    }
}

@Override
public void endDocument(){
    if(!found){
    System.out.println("Not Found");
    }
}

}

上面的事件处理程序确保始终输出某些内容,即使postcode在任何 XML 文件中都找不到,或者即使存在异常。所以,我期望上面的代码是println7464 次,但我得到了 50 行左右的输出。看起来循环实际上并没有为 each 运行,siteID但代码说它应该是。我已将问题缩小到上面显示的代码(很可能在循环本身内),但现在我看不出有任何问题。有什么建议么?

XML 看起来像这样,但有多达 300,000 个条目元素;

<?xml version="1.0"?>
<postcodes>
    <entry postcode='AB1 0AA' latitude='7.101478' longitude='2.242852' />
</postcodes>

很抱歉向你们倾倒了这么多代码,但我认为我不能用更少的代码给你们一个完整的画面。

4

1 回答 1

1

出现问题(下面,评论);

for (Integer id : siteID){           
            siteTable = em.find(SiteTable.class, id);
            XMLPositionRetriever.runXMLQuery(siteTable.getPostcode());// <--- Null point exception on this line.       
    }   

哪里em.find()没找到Entity类,就返回null。在这种情况下siteTable.getPostcode()被抛出NullPointerException。因此,我添加了一个 if 语句以防止空引用通过该语句(以及添加一些其他条件来整理 XML 搜索)。

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.");
       }
}

感谢MarioP,没有他我可能不会弄明白。

于 2013-09-04T09:40:16.177 回答