这是我用来学习 JXPath xml 解析的示例代码,
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"));
}
}
这是我使用的 XML 文件
<?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>
我收到以下错误,
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
我添加了 lib 文件,commons-jxpath-1.3.jar、commons-beanutils-1.3.jar、apache-commons-logging.jar。