java—在xml解析中面对org.xml.sax.saxparseexception异常

8wigbo56  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(676)

我已经在JavaSpringBoot应用程序中编写了一个调度程序,每小时运行一次,从上个月开始它就运行得非常好。但今天它在解析时已经开始抛出异常。我猜可能是xml(我从中获取的数据被破坏了,或者可能是它发生了一些我无法理解的变化)。
请注意:我不能更改源数据。
这是我的密码:

@Scheduled(fixedRate = 1*60*60*1000 , initialDelay = 10*1000)
    public String updateNewsFeed() {

        try {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String URL = "https://nation.com.pk/rss/coronavirus";
            Document doc = db.parse(URL);
            List<NewsFeed> newsFeedList = parseNewsItemsToList(doc);

            return "Works fine";

        } catch (Exception ex) {
            return ex.getMessage();
        }
}

public List<NewsFeed> parseNewsItemsToList(Document doc) throws Exception{
        doc.getDocumentElement().normalize();
        NodeList nodes = doc.getElementsByTagName("item");
        List<NewsFeed> newsFeedList = new ArrayList<>();
        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);

            NodeList title = element.getElementsByTagName("title");
            NodeList link = element.getElementsByTagName("link");
            NodeList description = element.getElementsByTagName("description");
            NodeList pubDate = element.getElementsByTagName("pubDate");
            NodeList guid = element.getElementsByTagName("guid");

            org.jsoup.nodes.Document htmlDoc = Jsoup.connect(link.item(0).getTextContent().trim()).get();
                /*Elements pngs = htmlDoc.select("picture");
                System.out.println("\nimg link:"+pngs.toString());*/

            String image = htmlDoc.select("picture").select("img[src~=(?i)\\.(png|jpe?g)]").attr("src").trim();
            newsFeedList.add(new NewsFeed(
                    title.item(0).getTextContent().trim(),
                    description.item(0).getTextContent().trim(),
                    pubDate.item(0).getTextContent().trim(),
                    guid.item(0).getTextContent().trim(),
                    image,
                    link.item(0).getTextContent().trim()
            ));
        }
        return newsFeedList;
    }

以下是错误消息: [Fatal Error] coronavirus:195:32: The entity name must immediately follow the '&' in the entity reference. org.xml.sax.SAXParseException; systemId: https://nation.com.pk/rss/coronavirus; lineNumber: 195; columnNumber: 32; The entity name must immediately follow the '&' in the entity reference. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:258) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339) at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:177) at com.i2p.covid19.service.NewsFeedService.updateNewsFeed(NewsFeedService.java:87) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748)

zed5wv10

zed5wv101#

问题是 & xml中的符号和字符。
Lifestyle & Entertainment & 是非法的外部xml文档 CDATA 部分。这必须写为 &amp; 但是xml文档的生产者已经逃脱了 & 性格。
如果你更换 &&amp; ,它会起作用的。
使用工具库(https://rometools.github.io/rome/)如果您的目标是处理rss提要,我建议使用 rome 处理特殊字符的库,如 & -它简单明了。参考https://www.baeldung.com/rome-rss
下面的代码片段打印 International News<title> rss源的标记:

URL feedSource = new URL("https://nation.com.pk/rss/coronavirus");
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedSource));
System.out.println(feed.getTitle());

相关问题