无法在具有<doctype>标记</doctype>的XML文件中从JAVA运行Xpath查询

时间:2011-01-25 15:00:46

标签: java xml dtd xml-parsing

我制作了以下方法,该方法在硬编码的XML文件中运行硬编码的xPath查询。该方法完美有一个例外。某些xml文件包含以下标记

           <!DOCTYPE WorkFlowDefinition SYSTEM "wfdef4.dtd"> 

当我尝试在该文件中运行查询时,我得到以下异常:

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

问题是:我该怎么做才能指示我的程序不要考虑这个DTD文件? 我还注意到路径C:\ ProgramFiles \ code \ other \ xPath \ wfdef4.dtd是我运行我的应用程序而不是实际xml文件所在的路径。

谢谢你的推荐

这是我的方法:

 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.printStackTrace();
  }
  return strBuffer.toString();
      }

1 个答案:

答案 0 :(得分:1)

答案是:

    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);