开发者

Cannot run Xpath queries from JAVA in XML files having <DOCTYPE> tag

开发者 https://www.devze.com 2023-02-06 10:44 出处:网络
I have made the following method which runs hard-coded xPath queries in a hard-coded XML file. The method works perfect with one exception. Some xml files contains the following tag

I have made the following method which runs hard-coded xPath queries in a hard-coded XML file. The method works perfect with one exception. Some xml files contains the following tag

           <!DOCTYPE WorkFlowDefinition SYSTEM "wfdef4.dtd"> 

When i try to run a query in that file i get the following exception:

     java.io.FileNotFoundException: 
     C:\ProgramFiles\code\other\xPath\wfdef4.dtd(The system cannot find the file specified). 

The question is : What can i do to instruct my program not to take under consideration this DTD file? I have also noted that the path C:\ProgramFiles\code\other\xPath\wfdef4.dtd is the one i run my application from and not the one that the actual xml file is located.

Thank you in advace

Here is my method:

 public String evaluate(String expression,File file){
  XPathFactory factory = XPathFactory.newInstance();
  xPath = XPathFactory.newInstance().newXPath();
  StringBuffer strBuffer = new StringBuffer();
  try{
    InputSource inputSource = new InputSource(new FileInputStream(file));
                         //evaluates the expression
    NodeList nodeList = (NodeList)xPath.evaluate(expression, 
                   inputSource,XPathConstants.NODESET);

                         //does other stuff, irrelevant with my question.
    for (int i = 0 ; i <nodeList.getLength(); i++){
     strBuffer.append(nodeList.item(i).getTextContent());
    }
  }catch (Exception e) {
   e.printSta开发者_StackOverflow中文版ckTrace();
  }
  return strBuffer.toString();
      }


And the answer is :

    xPath = XPathFactory.newInstance().newXPath();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //add this line to ignore dth DTD
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
0

精彩评论

暂无评论...
验证码 换一张
取 消