3-9 自由编程
来源:3-9 自由编程
慕的地2082093
2019-12-21 16:03:14
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<element name="teaching-plan">
<complexType>
<sequence>
<element name="course" minOccurs="1" maxOccurs="100">
<complexType>
<sequence>
<element name="course-name" type="string"></element>
<element name="class-hour" type="integer"></element>
<element name="exam-form" type="string"></element>
</sequence>
<attribute name="id" type="string" use="required"></attribute>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
<?xml version="1.0" encoding="UTF-8"?>
<!-- <!DOCTYPE teaching-plan SYSTEM "plan.dtd"> -->
<teaching-plan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="plan.xsd">
<course id="001">
<course-name>大学英语</course-name>
<class-hour>34</class-hour>
<exam-form>考试</exam-form>
</course>
<course id="002">
<course-name>高等数学</course-name>
<class-hour>70</class-hour>
<exam-form>考试</exam-form>
</course>
<course id="003">
<course-name>计算机应用基础</course-name>
<class-hour>108</class-hour>
<exam-form>上机考试</exam-form>
</course>
</teaching-plan>
package lib;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class XPathTestor {
public void xpath(String xpathExp) {
String file="C:/Users/Admin/eclipse-workspace/xml/src/plan.xml";
SAXReader reader=new SAXReader();
try {
Document document=reader.read(file);
List<Node> nodes=document.selectNodes(xpathExp);
for(Node node:nodes) {
Element element=(Element)node;
System.out.println(element.attributeValue("id"));
System.out.println(element.elementText("course-name"));
System.out.println(element.elementText("class-hour"));
System.out.println(element.elementText("exam-form"));
System.out.println("============================================");
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
XPathTestor xpath=new XPathTestor();
System.out.println("获取所有课程信息");
//xpath.xpath("/teaching-plan/course");
xpath.xpath("//course");
System.out.println("查询课时小于50的课程信息");
xpath.xpath("//course[class-hour < 50]");
System.out.println("查询课程名为高等数学的课程信息");
xpath.xpath("//course[course-name='高等数学']");
System.out.println(" 查询属性id为001的课程信息");
//xpath.xpath("//course[1]");
xpath.xpath("//course[@id=001]");
System.out.println("查询前两条课程信息");
xpath.xpath("//course[1] | //course[2]");
//xpath.xpath("//course[position()<2]");
}
}
1回答
好帮手慕酷酷
2019-12-21
同学你好,代码完成的很棒!加油!
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题