Android org.xmlpull.v1.XmlPullParserException while parsing XML

拥有回忆 提交于 2019-11-30 20:16:01

Yes, the exception is probably thrown because that is invalid XML as per section 2.4 Character Data and Markup in the XML 1.0 specification:

[...] the left angle bracket (<) MUST NOT appear in [its] literal form, [...]

If you put that XML in Eclipse, Eclipse will complain about the XML being invalid. If you are able to fix the web service, you should fix the generated XML, either by using entity references such as &lt; or by using CDATA.

If you have no power over the web service, I think the easiest will be to parse that manually with some custom code, perhaps using regular expressions, depending on how relaxed requirements of generality you have.

Example Code

Here's how you could parse the XML file above. Note that you probably want to improve this code to make it more general, but you should have something to start with at least:

    // Read the XML into a StringBuilder so we can get get a Matcher for the
    // whole XML
    InputStream xmlResponseInputStream = // Get InputStream to XML somehow
    InputStreamReader isr = new InputStreamReader(xmlResponseInputStream);
    BufferedReader br = new BufferedReader(isr);
    StringBuilder xmlAsString = new StringBuilder(512);
    String line;
    try {
        while ((line = br.readLine()) != null) {
            xmlAsString.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Look for links using a regex. Assume the first link is "Prev" and the
    // next link is "Next"
    Pattern hrefRegex = Pattern.compile("<a href=\"([^\"]*)\">");
    Matcher m = hrefRegex.matcher(xmlAsString);
    String linkToPrevPost = null;
    String linkToNextPost = null;
    while (m.find()) {
        String hrefValue = m.group(1);
        if (linkToPrevPost == null) {
            linkToPrevPost = hrefValue;
        } else {
            linkToNextPost = hrefValue;
        }
    }

    Log.i("Example", "'Prev' link = " + linkToPrevPost + 
            " 'Next' link = " + linkToNextPost);

With your XML file, the output to logcat will be

I/Example (12399): 'Prev' link = link-to-prev-post 'Next' link = link-to-next-post
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!