0

我无法弄清楚 JDOMException 被捕获的原因。我将 XML 格式字符串传递给 SAXBulider 的构建函数以获取文档,此处抛出异常。

存储在字符串结果中的 XML 字符串:

<?xml version='1.0' encoding='ISO-8859-1'?><results><result cover="http://cps-static.rovicorp.com/3/JPG_170/MI0002/213/MI0002213251.jpg?partner=allrovi.com" title="Hey-Ya" artist="A.D.D." year="N/A" genre="Pop/Rock" details="http://www.allmusic.com/album/hey-ya-mw0001029555"/><result cover="http://cps-static.rovicorp.com/3/JPG_170/MI0003/152/MI0003152820.jpg?partner=allrovi.com" title="Heyma" artist="Abir Nasraoui" year="N/A" genre="Latin, Pop/Rock" details="http://www.allmusic.com/album/heyma-mw0002115440"/><result cover="http://cs-server.usc.edu:14186/album.jpg" title="Heyla" artist="Candy" year="2003" genre="R&B" details="http://www.allmusic.com/album/heyla-mw0000698853"/><result cover="http://cps-static.rovicorp.com/3/JPG_170/MI0002/172/MI0002172691.jpg?partner=allrovi.com" title="Heya" artist="Jimmy Stallings" year="2003" genre="International" details="http://www.allmusic.com/album/heya-mw0000336392"/><result cover="http://cps-static.rovicorp.com/3/JPG_170/MI0003/361/MI0003361503.jpg?partner=allrovi.com" title="Heya" artist="David Jones" year="N/A" genre="Electronic" details="http://www.allmusic.com/album/heya-mw0002388044"/></results>

导致异常的部分代码是:

SAXBuilder builder = new SAXBuilder();

    String temp="";

    out.println("Inside Servlet :::: ");

    try
    {
        out.println("1. HERE");
        Document doc = builder.build(new StringReader(results));
        out.println("2. HERE");
        Element root=doc.getRootElement();
        out.println(root);  
        List resultChildren=root.getChildren();
        out.println("3. HERE");
        if(resultChildren.size()==0)
        {
            out.println("{\"results\":[]}");
            return;
        }           
        temp="{\"results\":{\"result\":[";
        for(int i=0;i<resultChildren.size();i++)
        {
            Element tempElem = (Element)(resultChildren.get(i));

            if(i>0)
            temp+=",";

            if((request.getParameter("type")).equals("Artists"))                    
                 temp+=parseArtists(tempElem);                   
            else if((request.getParameter("type")).equals("Albums"))
                temp+=parseAlbums(tempElem);
            else                    
                temp+=parseSongs(tempElem);                                                         
        }
        temp+="]}}";
    }
    catch(JDOMException ex)
    {
        errors+="1.Could not parse xml file";           
    }
    catch(IOException ex)
    {
        errors+="2.Could not parse xml file";           
    }

使用 PrintWriter 生成的输出如下:

Inside Servlet :::: 
1. HERE
{"errors": {"1.Could not parse xml file"}}

因此,在 doc=builder.build(new StringReader(results)); 处抛出异常。

请指导我解决这个问题。

4

1 回答 1

2

在打印堆栈跟踪(或至少是异常消息)之后,您会看到输入 XML 格式不正确:有一个包含字符串的属性"R&B"。& 符号恰好是少数几个必须转义的字符之一,在这种情况下它应该是:"R&amp;B".

于 2013-04-07T11:22:49.553 回答