有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何找到给定的字符串是RSS提要还是非RSS提要

我有一个字符串,它从给定Url下载的数据中获取XML和HTML输入。在通过SAXParser进行解析之前,我想检查下载的字符串是否是html文档的rss提要。怎么找到这个

比如说

如果我从http://rss.cnn.com/rss/edition.rss下载一个数据,得到的字符串就是一个rss提要

如果我从http://edition.cnn.com/2014/06/19/opinion/iraq-neocons-wearing/index.html下载一个数据,结果字符串就是一个html文档

如果字符串是rss提要,我想继续我的过程


共 (1) 个答案

  1. # 1 楼答案

    RSS和HTML都是XML的子集。因此,您可以以XML的形式获取数据,并根据RSSXSD对其进行验证。像这样

    URL schemaFile = new URL("http://europa.eu/rapid/conf/RSS20.xsd");
    Source xmlFile = new StreamSource(YOUR_URL_HERE);
    SchemaFactory schemaFactory = SchemaFactory
        .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    try {
      validator.validate(xmlFile);
      // at this line you can be sure it's RSS 2.0 stream
    } catch (SAXException e) {
      // NOT RSS
    }
    

    若你们想检查这个字符串,你们可以检查它的典型rss结构,比如根元素,中的必需元素。但我不推荐