5

I currently have the following XML file.

http://www.cse.unsw.edu.au/~cs9321/14s1/assignments/musicDb.xml

My XMLParser.java class.

package edu.unsw.comp9321.assignment1;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class XMLParser {


public void search () {

    try{
        File fXmlFile = new File("/COMP9321Assignment1/xml/musicDb.xml");           
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

I create an object in another class and call the search but I keep receiving the above stated error.

Would anyone know what the problem might be?

Thanks for your help.

  • The file /COMP9321Assignment1/xml/musicDb.xml doesn't exist, or doesn't contain what you think it contains. You realize that it's an absolute path, which will thus literally look for a directory COMP9321Assignment1 under the root of the file system, right? – JB Nizet Apr 06 '14 at 08:01
  • Oh right. Where am I supposed to put this `.xml` file? And how should I refer to it? –  Apr 06 '14 at 08:16
  • Put it anywhere you want to, and use the path of the actual file in your code. – JB Nizet Apr 06 '14 at 08:17
  • Thanks JB Nizet. I just created a `res` folder and set the file path as `File fXmlFile = new File("C:/Users/Giridhaar/workspace/COMP9321Assignment1/res/musicDb.xml");`. This worked. I'm curious, if I were to run this project on another computer how would it find the file? –  Apr 06 '14 at 08:42
  • File paths are typically passed as argument of a program. If you want to open a file in notepad, you type `notepad c:\path\of\file.txt`. Your program should probably take the file path as argument. – JB Nizet Apr 06 '14 at 08:46
  • I haven't received any error. Here is the output :`Root element :musicDB` – Braj Apr 06 '14 at 14:37

1 Answers1

4

Normally "org.xml.sax.SAXParseException: Premature end file" occurrs due to several reasons

1.Check your xml were all the tags are closed properly at same level

2.check if any name space issues.

3.check for welformness of your xml document

Naveen
  • 535
  • 3
  • 14