Search code examples
javaxmlurlapache-commons

Apache common jxpath XML parse - XML URL is null


here is an example code which i have used to learn about JXPath xml parsing,

import java.net.URL;
import java.util.Iterator;

import org.apache.commons.jxpath.Container;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.xml.DocumentContainer;

public class DocumentContainerTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        //Get the URL the of XML document
        URL url = DocumentContainerTest.class.getClassLoader().getResource("student_class.xml");

        //Construct document container from the URL to XML
        Container container = new DocumentContainer(url);

        JXPathContext context = JXPathContext.newContext(container);

        Iterator<?> subjects = context.iterate("/studentClass/subjects_list/subject");
        while (subjects.hasNext()) {
            System.out.println(subjects.next());
        }

        Iterator<?> stdNames = context.iterate("/studentClass/student_list/student/firstName");
        while (stdNames.hasNext()) {
            System.out.println(stdNames.next());
        }

        System.out.println(context.getValue("/studentClass/student_list/student[@id='1']/firstName"));
    }

}

and here is my XML File used

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<studentClass>
    <name>MPC</name>
    <subjects_list>
        <subject>Maths</subject>
        <subject>Physics</subject>
        <subject>Chemistry</subject>
    </subjects_list>
    <student_list>
        <student id="1">
            <age>2</age>
            <dob>2011-09-25T16:41:56.250+05:30</dob>
            <firstName>Sriram</firstName>
            <hobby>Painting</hobby>
            <lastName>Kasireddi</lastName>
        </student>
        <student id="2">
            <age>26</age>
            <dob>2011-09-25T16:41:56.250+05:30</dob>
            <firstName>Sudhakar</firstName>
            <hobby>Coding</hobby>
            <lastName>Kasireddi</lastName>
        </student>
    </student_list>
</studentClass>

i am getting the below error,

Exception in thread "main" org.apache.commons.jxpath.JXPathException: XML URL is null
    at org.apache.commons.jxpath.xml.DocumentContainer.<init>(DocumentContainer.java:106)
    at org.apache.commons.jxpath.xml.DocumentContainer.<init>(DocumentContainer.java:92)
    at org.apache.commons.jxpath.XMLDocumentContainer.<init>(XMLDocumentContainer.java:58)
    at jxpath_ex1.DocumentContainerTest.main(DocumentContainerTest.java:26)
Java Result: 1

i have added the lib files, commons-jxpath-1.3.jar, commons-beanutils-1.3.jar, apache-commons-logging.jar.


Solution

  • in defining the url have tried out like below and it works !

     URL url = DocumentContainerTest.class.getResource("student_class.xml");