的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”);
答
,而不是只检查if (file != null)
检查文件是否存在if (file.exists())
。可能的问题是文件不存在于该路径
答
您的代码工作正常。
检查得到的文件
if(xml_doc == null)
System.out.println("Doc is null");
else
System.out.println("Doc is not null");
后的状态,你会得到
Doc is not null
当您尝试打印文档,它会给
[#document: null]
您可以执行的操作输出通过该文档对象。
你会得到'错误:找不到XML文件!'或堆栈跟踪? –
检查文件是否存在。如果问题无法解决,然后发布堆栈堆栈跟踪 –
是的,我得到这个消息 – Aviadjo