在java中制作rss feed解析器

时间:2013-08-12 16:28:41

标签: java xpath xml-parsing rss

我正在尝试创建一个将url和xpath作为参数的函数,并从提供的url查询xml文件并返回String结果。这是我的代码:`package

uforia.tests.daoTests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;


import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class XpathHelper {

    public static final String NL = System.getProperty("line.separator");  

    @Test
    public void testBelow() {

        System.out.println(xmlQuery("http://abcnews.go.com/US/wireStory/10-things-today-19933443", "//*[@id=\"storyText\"]/p[3]"));

        Assert.assertTrue(true);
    }


    public String xmlQuery(String url, String xpath) {

        StringBuilder sb = new StringBuilder();

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); // Getting
                                                                                  // the
                                                                                  // instance
                                                                                  // of
                                                                                  // DocumentBuilderFactory
        domFactory.setNamespaceAware(true); // true if the parser produced will
                                            // provide support for XML
                                            // namespaces;

        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            // Creating document builder

            Document doc = builder.parse(new URL(url).openStream()); // e.g.

            XPath xPath = XPathFactory.newInstance().newXPath();
            // getting instance of xPath

            XPathExpression expr = xPath.compile(xpath);
            // e.g. "//@id"
            NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < nodes.getLength(); i++) {
                sb.append(nodes.item(i).getNodeValue()).append(NL);
            }

        }

        catch (Exception e) {
            e.printStackTrace();
        }
        // Think of closing connection in finnaly branch...
        return sb.toString();

    }

}
`

我收到了这个错误:

  

[致命错误]:37:108:对实体“资产”的引用必须以   ';'分隔符。 org.xml.sax.SAXParseException; lineNumber:37;   columnNumber:108;对实体“资产”的引用必须以   ';'分隔符。

我认为问题在于逃避&符号,但我无法让它工作。

提前感谢您的帮助......

0 个答案:

没有答案