Aviadjo
Aviadjo

Reputation: 655

Java: reading and parsing XML file always return null

i have XML file i try to read to a Document object:

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

and i try to read it into Document object by code:

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

i always get xml_doc NULL can someone help me solve the problem?

I Always get that the file doesn't exist, is use: Document doc = XMLReader.Get_XML_Document("C:\MCSA\MCSA_config.xml");

Upvotes: 0

Views: 4163

Answers (2)

Dhinakar
Dhinakar

Reputation: 4151

Your code working fine.

Check the condition after getting document

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

You will get

Doc is not null

When you try to print the document it will give the output

[#document: null]

You can perform operation through that document object.

Upvotes: 0

vishal_aim
vishal_aim

Reputation: 7854

instead of just checking if (file != null) check whether file exists or not if (file.exists()). Possible issue is file does not exist at that path

Upvotes: 1

Related Questions