0

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

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;行号:37;列号:108;对实体“资产”的引用必须以“;”结尾 分隔符。

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

提前感谢您的帮助...

4

0 回答 0