的Java:读取和解析XML文件始终返回null

问题描述:

我有XML文件,我尝试读取一个文件对象:的Java:读取和解析XML文件始终返回null

<MCSA_Configuration> 
    <Variables> 
     <python27_path> C:\Python27\python.exe </python27_path> 
     <python32_path> C:\Python32\python.exe </python32_path> 
     <xlrd> xlrd-ok </xlrd> 
    </Variables> 
</MCSA_Configuration> 

,我试图通过代码读取到Document对象:

import java.io.File; 
    import java.text.DecimalFormat; 
    import java.util.ArrayList; 
    import javax.xml.parsers.DocumentBuilder; 
    import javax.xml.parsers.DocumentBuilderFactory; 
    import org.w3c.dom.Document; 
    import org.w3c.dom.NamedNodeMap; 
    import org.w3c.dom.Node; 
    import org.w3c.dom.NodeList; 

public static Document Get_XML_Document(String xml_file_path) { 

     File file; 
     Document xml_doc = null; 
     // TODO code application logic here 
     try { 
      file = new File(xml_file_path); 
      if (file.exists()) { 
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); 
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); 
        xml_doc = docBuilder.parse(file); 
      } else { 
       System.out.println("Error: XML File not found!"); 
      } 

     } catch (Exception ex) { 
      System.out.println(ex.getMessage()); 
     } 
     return xml_doc; 
    } 

我总是得到xml_doc NULL 有人可以帮我解决问题吗?

我总是得到该文件不存在,使用: Document = XMLReader.Get_XML_Document(“C:\ MCSA \ MCSA_config.xml”);

+2

你会得到'错误:找不到XML文件!'或堆栈跟踪? –

+0

检查文件是否存在。如果问题无法解决,然后发布堆栈堆栈跟踪 –

+0

是的,我得到这个消息 – Aviadjo

,而不是只检查if (file != null)检查文件是否存在if (file.exists())。可能的问题是文件不存在于该路径

+0

我总是得到该文件不存在,是使用: 书籍DOC = XMLReader.Get_XML_Document(“C:\\ \\ MCSA MCSA_config.xml” ); 和该文件是真的在那里.. – Aviadjo

+0

你也可以尝试与正斜杠,例如'XMLReader.Get_XML_Document(“C:/MCSA/MCSA_config.xml”);' –

+0

听起来好像你的文件名可能有尾随空格,或者文件扩展名不会显示在窗口中,而该文件实际上是MCSA_config.xml.txt – IDKFA

您的代码工作正常。

检查得到的文件

if(xml_doc == null) 
    System.out.println("Doc is null"); 
else 
    System.out.println("Doc is not null"); 

后的状态,你会得到

Doc is not null

当您尝试打印文档,它会给

[#document: null]

您可以执行的操作输出通过该文档对象。