java无法打印给定节点的输出。只能打印根元素
我刚刚开始学习基于教程的JAVA xml=DOM4J,它在解析xml代码时更加灵活。因此,我着重于更多地理解DOM4J,因为与DOM解析器和JDOM相比,它的编码更少
我在打印节点的输出时遇到问题。任何帮助都将不胜感激!请容忍我,因为我仍在学习如何使用它,并更加熟悉它。为了更好地理解,请以简单的方式解释如何正确地执行它。谢谢大家!
我的代码基于TutorialPoint
try {
String src = "student.xml";
File inputFile = new File(src);
SAXReader reader = new SAXReader();
Document doc = reader.read(inputFile);
System.out.println("Root element: "
+ doc.getRootElement().getName());
Element classElement = doc.getRootElement();
List<Node> nodes = doc.selectNodes("/Section/Student");
for (Node node : nodes){
System.out.println("First Name" + node.selectSingleNode("FirstName").getText());
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是我的XML文件
<?xml version = "1.0"?>
<Section>
<Student>
<Idnumber>0000001</Idnumber>
<FirstName>Cat</FirstName>
<LastName>Dog</LastName>
</Student>
</Section>
我在控制台中收到的错误如下:
Root element :Section
Exception in thread "main" java.lang.NoClassDefFoundError:org/jaxen/JaxenException
at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)
at com.dls.csb.ParsingXML.main(ParsingXML.java:30)
# 1 楼答案
引用TutorialsPoint article on dom4j
显然,类路径中没有jaxen jar。如果你有dom4j-1.6.1。zip存档,您可以在
lib
文件夹中找到一个jaxen jar我用jaxen jar在类路径上运行了你的代码,它成功地运行了。你的代码似乎在做你想做的事情,只是你不太具备所有的依赖性
Jaxen是一个javaxpath库,其中的文本
/Section/Student
是一个XPath表达式,用于选择作为根
Section
元素的子元素的所有Student
元素