如何抑制java xpath错误

时间:2012-11-09 00:36:56

标签: java xml xpath xml-parsing

当我运行下面的代码时,我收到了:

[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

我知道字符串html不允许内容,但我想抑制所有错误。

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.w3c.dom.*;
import org.xml.sax.InputSource;

import javax.xml.xpath.*;
import javax.xml.parsers.*;
public class Test {

    public static void main(String[] args){
        String html="---<html><div id='teste'>Teste</div><div id='ola'>Ola tudo ebm!</div></html>";

        try{

            XPath xpath = XPathFactory.newInstance().newXPath();
            String xpathExpression = "//div[@id='ola']";

            InputStream is = new ByteArrayInputStream(html.getBytes()); 
            InputSource inputSource = new InputSource(is);

            NodeList nodes = (NodeList) xpath.evaluate
            (xpathExpression, inputSource, XPathConstants.NODESET);

            int j = nodes.getLength();

            for (int i = 0; i < j; i++) {
                System.out.println(nodes.item(i).getTextContent());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:0)

我试图操纵你的HTML,一切都适合我。 当我尝试XpathEvaluate时,我确认我也是一个空值 这就是我绕过它的方式:)

    try {

        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("D:\\Loic_Workspace\\Test2\\res\\test.xml"));


        Integer length = doc.getElementsByTagName("div").getLength();


        if(length != null){

            for(int i=0;i<length;i++){


                if(doc.getElementsByTagName("div").item(i).getAttributes().item(0).getTextContent().equals("ola")){
                    System.out.println(doc.getElementsByTagName("div").item(i).getTextContent());
                }



            }


        }





    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

控制台输出:Ola tudo ebm!

doc.getElementsByTagName(“div”)。item(i).getAttributes()。item(0) - &gt;是文档中'id'属性的引用。我通过.getText()方法检索此元素的文本内容。

我知道这不是最有效的方法,但它有效:)

希望它有所帮助,