例11、用XML作为持久化设备实现考生成绩管理系统
1、以如下格式的exam.xml文件为例
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<exam>
<student idcard="111" examid="222">
<name>张三</name>
<location>沈阳</location>
<grade>89</grade>
</student>
<student idcard="333" examid="444">
<name>李四</name>
<location>大连</location>
<grade>97</grade>
</student>
</exam>
2、编程实现如下功能
3、实现学生信息的添加
4、实现学生信息的查询
5、实现学生的删除功能
第一步、exam.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- ctrl+shift+f可以格式化一段xml代码,使其变得整齐 --><exam>
<student examid="222" idcard="111">
<name>张三</name>
<location>沈阳</location>
<grade>89</grade>
</student>
<student examid="444" idcard="333">
<name>李四</name>
<location>大连</location>
<grade>97</grade>
</student>
</exam>
第二步、Student.java
package fandong.domain;
public class Student {
private String idcard;
private String examid;
private String name;
private String location;
private double grade;
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getExamid() {
return examid;
}
public void setExamid(String examid) {
this.examid = examid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
}
第三步、XmlUtils.java
package fandong.Utils;
import java.io.FileOutputStream;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.parsers.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class XmlUtils {
private static String filename="src/exam.xml";
public static Document getDocument() throws Exception{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(filename);
return document;
}
public static void write2Xml(Document document)throws Exception{
TransformerFactory factory=TransformerFactory.newInstance();
Transformer t=factory.newTransformer();
t.transform(new DOMSource(document), new StreamResult(new FileOutputStream(filename)));
}
}
第四步、StudentDao.java
package fandong.dao;
import org.w3c.dom.*;
import fandong.Exception.StudentNotExistException;
import fandong.Utils.XmlUtils;
import fandong.domain.Student;
public class StudentDao {
public void add(Student s){
try {
Document document=XmlUtils.getDocument();//checked Exception(编译器异常)
//创建出封转学生的标签
Element student_tag=document.createElement("student");
student_tag.setAttribute("idcard", s.getIdcard());
student_tag.setAttribute("examid", s.getExamid());
//创建用于封装学生姓名、所在地和成绩的标签
Element name=document.createElement("name");
Element location=document.createElement("location");
Element grade=document.createElement("grade");
name.setTextContent(s.getName());
location.setTextContent(s.getLocation());
grade.setTextContent(s.getGrade()+"");
student_tag.appendChild(name);
student_tag.appendChild(location);
student_tag.appendChild(grade);
//把封装了的学生信息标签挂到文档上
document.getElementsByTagName("exam").item(0).appendChild(student_tag);
//更新内存
XmlUtils.write2Xml(document);
} catch (Exception e) {
throw new RuntimeException(e);//转化为运行时异常,注意这里的e
}
}
public Student find(String examid){
try {
Document document=XmlUtils.getDocument();
NodeList list=document.getElementsByTagName("student");
for(int i=0;i<list.getLength();i++){
Element student_tag=(Element)list.item(i);
if(student_tag.getAttribute("examid").equals(examid)){
//找到与examid相匹配的学生,new出一个student对象封装这个学生的信息返回
Student s=new Student();
s.setExamid(examid);
s.setIdcard(student_tag.getAttribute("idcard"));
s.setName(student_tag.getElementsByTagName("name").item(0).getTextContent());
s.setLocation(student_tag.getElementsByTagName("location").item(0).getTextContent());
s.setGrade(Double.parseDouble(student_tag.getElementsByTagName("grade").item(0).getTextContent()));
return s;
}
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void delete(String name)throws StudentNotExistException{
try {
Document document=XmlUtils.getDocument();
NodeList list=document.getElementsByTagName("name");
for(int i=0;i<list.getLength();i++){
if(list.item(i).getTextContent().equals(name)){
list.item(i).getParentNode().getParentNode().removeChild(list.item(i).getParentNode());
XmlUtils.write2Xml(document);
return;
}
}
throw new StudentNotExistException(name+"不存在");
}catch (StudentNotExistException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
第五步、StudentNotExistException.java
package fandong.Exception;
public class StudentNotExistException extends Exception {
public StudentNotExistException() {
}
public StudentNotExistException(String message) {
super(message);
}
public StudentNotExistException(Throwable cause) {
super(cause);
}
public StudentNotExistException(String message, Throwable cause) {
super(message, cause);
}
}
第六步、StudntDao.java
package junit.test;
import org.junit.Test;
import fandong.Exception.StudentNotExistException;
import fandong.dao.StudentDao;
import fandong.domain.Student;
public class StudentDaoTest {
@Test
public void testAdd(){
StudentDao dao=new StudentDao();
Student s=new Student();
s.setExamid("121");
s.setGrade(89);
s.setIdcard("122");
s.setLocation("北京");
s.setName("aa");
dao.add(s);
}
@Test
public void testFind(){
StudentDao dao=new StudentDao();
dao.find("121");//断点测试:在此打上断点,然后在右边testFind()点击右键选中Debug as,切换到debug
//视图,然后将本行用鼠标选中,然后用右键watch,测试完了 之后,要停止程序的运行,并且将breadPoint
//视图里面的各个变量清除!
}
@Test
public void testDelete() throws StudentNotExistException{
StudentDao dao=new StudentDao();
dao.delete("aa");
}
}
第七步、Main.java
package fandong.UI;
import java.io.*;
import fandong.Exception.StudentNotExistException;
import fandong.dao.StudentDao;
import fandong.domain.Student;
public class Main {
public static void main(String[] args) {
try{
System.out.println("添加用户(a) 删除用户(b)查找用户(c)");
System.out.print("请输入造作类型:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String type=br.readLine();
if("a".equals(type)){
System.out.print("请输入学生姓名:");
String name=br.readLine();
System.out.print("请输入学生准考证号:");
String examid=br.readLine();
System.out.print("请输入学生身份证号:");
String idcard=br.readLine();
System.out.print("请输入学生所在地:");
String location=br.readLine();
System.out.print("请输入学生成绩:");
String grade=br.readLine();
Student s=new Student();
s.setExamid(examid);
s.setGrade(Double.parseDouble(grade));
s.setIdcard(idcard);
s.setLocation(location);
s.setName(name);
StudentDao dao=new StudentDao();
dao.add(s);
System.out.println("添加成功");
}else if("b".equals(type)){
System.out.println("请输入要删除的学生姓名");
String name=br.readLine();
try{
StudentDao dao=new StudentDao();
dao.delete(name);
System.out.println("删除成功");}
catch(StudentNotExistException e)
{
System.out.println("您要删除的学生不存在!");
}
}else if("c".equals(type)){
}else{
System.out.println("不支持您的操作!");
}
}
catch(Exception e){
e.printStackTrace();
System.out.println("对不起,我出错了!");
}
}
}
例12、SAX解析XML文档,获取文档所有标签及属性。
package fandong;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
public class Demo5 {
//sax解析xml文档
public static void main(String[] args) throws Exception{
//1、创建解析工厂
SAXParserFactory factory=SAXParserFactory.newInstance();
//2、得到解析器
SAXParser sp=factory.newSAXParser();
//3、得到读取器
XMLReader reader=sp.getXMLReader();
//4、设置内容处理器
reader.setContentHandler(new ListHandler());
//5、读取xml文档内容
reader.parse("src/fandong/config.xml");
}
}
//得到xml文档的所有内容
class ListHandler implements ContentHandler{
public void startElement(String uri, String localName, String qName/*标签名*/,Attributes atts) throws SAXException {
System.out.println("<"+qName+">");
//获取标签属性
for(int i=0;atts!=null&&i<atts.getLength();i++){//注意这行代码中的atts!=null
String attName=atts.getQName(i);
String attValue=atts.getValue(i);
System.out.println(attName+"="+attValue);
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("</"+qName+">");
}
public void characters(char[] ch, int start, int length) throws SAXException {
System.out.println(new String(ch,start,length));
}
public void setDocumentLocator(Locator locator) {}
public void startDocument() throws SAXException {}
public void endDocument() throws SAXException {}
public void startPrefixMapping(String prefix, String uri)throws SAXException {}
public void endPrefixMapping(String prefix) throws SAXException {}
public void ignorableWhitespace(char[] ch, int start, int length)throws SAXException {}
public void processingInstruction(String target, String data)throws SAXException {}
public void skippedEntity(String name) throws SAXException {}
}
例13、SAX解析XML文档,获取指定标签的内容。
package fandong;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
public class Demo6 {
//sax解析xml文档
public static void main(String[] args) throws Exception{
//1、创建解析工厂
SAXParserFactory factory=SAXParserFactory.newInstance();
//2、得到解析器
SAXParser sp=factory.newSAXParser();
//3、得到读取器
XMLReader reader=sp.getXMLReader();
//4、设置内容处理器
reader.setContentHandler(new TagValueHandler());
//5、读取xml文档内容
reader.parse("src/fandong/config.xml");
}
}
//得到xml文档中指定内容的标签
class TagValueHandler extends DefaultHandler{
//获取继承的方法:在空白处点击右键--->source-->Override and Implement Methods
private String currentTag;//记住当前解析到的是什么标签
private int needNumber=2;//记住想获取第几个作者标签的值
private int currentNumber;//当前解析的是第几个
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentTag=qName;
if(currentTag.equals("作者")){
currentNumber++;
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentTag=null;
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if("作者".equals(currentTag)&¤tNumber==needNumber){
System.out.println(new String(ch,start,length));
}
}
}
例14、sax解析案例之javabean封装xml文档数据。
第一步、Book.java
package fandong;
public class Book {
private String name;
private String author;
private String price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
第二步、Demo7.java
package fandong;
import java.util.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Demo7 {
//sax解析xml文档
public static void main(String[] args) throws Exception{
//1、创建解析工厂
SAXParserFactory factory=SAXParserFactory.newInstance();
//2、得到解析器
SAXParser sp=factory.newSAXParser();
//3、得到读取器
XMLReader reader=sp.getXMLReader();
//4、设置内容处理器
BeanListHandler handler=new BeanListHandler();
reader.setContentHandler(handler);
//5、读取xml文档内容
reader.parse("src/fandong/config.xml");
List<Book> list=handler.getBooks();//在此处打上断点,然后在空白处点击右键_-->debug as执行一次选中listwatch 在视图窗口中可以看到有两个Book对象
System.out.println(list);
}
}
//把XML文档中的每一本书封装到一个book对象,并把多个book对象放在一个list对象里面给
class BeanListHandler extends DefaultHandler{
private List list=new ArrayList();
private String currentTag;
private Book book;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentTag=qName;
if(currentTag.equals("书")){
book=new Book();
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equals("书")){
list.add(book);
book=null;
}
currentTag=null;//这里要置为空,否则会有异常
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if("书名".equals(currentTag)){
String name=new String(ch,start,length);
book.setName(name);
}
else if("作者".equals(currentTag)){
String author=new String(ch,start,length);
book.setAuthor(author);
}
else if("售价".equals(currentTag)){
String price=new String(ch,start,length);
book.setPrice(price);
}
}
public List<Book> getBooks() {//因为list是私有的
return list;
}
}
第三步、config.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><书架>
<书 context="xxxx">
<书名 name="xxx">Java就业培训教程</书名>
<作者>张孝祥</作者>
<售价>109元</售价><售价>109元</售价>
</书>
<书>
<书名>Javascript网页开发</书名>
<作者>黎活明</作者>
<售价>28.8</售价>
</书>
</书架>
例15、去掉上面例程当中endElement函数当中的
currentTag=bull;的语句,然后采用断点跟踪方式,分析程序的问题。
例16、使用dom4j对XML文档进行增删改查。
package dom4j;
import java.io.*
import java.util.List;
import org.dom4j.*;
import org.dom4j.io.*;
import org.junit.Test;
public class Demo1 {
public static void main(String[] args) throws Exception{
//read();
//delete();
update();
}
//读取xml文档第二本书的书名<书名 name="lhm">Javascript网页开发</书名>
//并得到第二本书书名的属性
public static void read() throws DocumentException{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/fandong/config.xml"));
Element root=document.getRootElement();
Element book=(Element)root.elements("书").get(1);
String value=book.element("书名").getText();
System.out.println(value);
String valueAttr=book.element("书名").attribute("name").getValue();
//上面一行等同于String valueAttr=book.element("书名").attributeValue("name");
System.out.println(valueAttr);
}
//在第一本书上添加一个新的售价:<售价>209元</售价>
//运行时XML会有乱码,是SUN公司IO流的问题
public static void add()throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/fandong/config.xml"));
Element book=document.getRootElement().element("书");//得到第一本书
book.addElement("售价").setText("209元");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
//XMLWriter writer = new XMLWriter(new FileWriter( "src/fandong/config.xml" ));
//使用FileWriter默认GB2312进行存储,所以会出现乱码
XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/fandong/config.xml" ),"UTF-8"),format);
//也可以这样:XMLWriter writer = new XMLWriter(new FileOutputStream("src/fandong/config.xml"),format);
writer.write( document );
writer.close();
}
//在第一本书指定位置添加一个新的售价:<售价>209元</售价>,更改包含了所有孩子的list集合
public static void add2()throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/fandong/config.xml"));
Element book=document.getRootElement().element("书");//得到第一本书
List list=book.elements();//[书名,作者,售价]
Element price=DocumentHelper.createElement("售价");
price.setText("309.00元");
list.add(2, price);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/fandong/config.xml" ),"UTF-8"),format);
writer.write( document );
writer.close();
}
//删除上面添加的结点
public static void delete()throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/fandong/config.xml"));
Element price=document.getRootElement().element("书").element("售价");
price.getParent().remove(price);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/fandong/config.xml" ),"UTF-8"),format);
writer.write( document );
writer.close();
}
public static void update()throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/fandong/config.xml"));
Element book=(Element) document.getRootElement().elements("书").get(1);
book.element("作者").setText("樊冬");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/fandong/config.xml" ),"UTF-8"),format);
writer.write( document );
writer.close();
}
}
例17、XPath实例之用户登录系统。
Step1、user.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<users>
<user id="1" username="aaa" password="123" email="aa@sina.com"></user>
<user id="2" username="bbb" password="123" email="bb@sina.com"></user>
</users>
Step2、Demo9.java
package fandong;
import java.io.File;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
//查找users.xml文档是否有和用户匹配的用户名和密码
public class Demo9 {
public static void main(String[] args) throws Exception {
String username="aaa";
String password="123";
//检测xml文档是否有匹配的用户名和密码
SAXReader reader=new SAXReader();
Document document=reader.read(new File("src/fandong/users.xml"));
Node node=document.selectSingleNode("//user[@username='"+username+"' and @password='"+password+"']");//注意这里的and
//注意这里的单引号,这里断字符串:先打两个双引号,再打两个加号,在中间加入字符串变量,即"+字符串变量+"
if(node==null){
System.out.println("没有匹配的用户");
}
else{
System.out.println("登陆成功");
}
}
}
例18、xml schema实例1。
Book.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.itcast.cn"
elementFormDefault="qualified"
>
<xs:element name="书架">
<xs:complexType>
<xs:sequence maxOccurs='unbounded'>
<xs:element name="书">
<xs:complexType>
<xs:sequence>
<xs:element name="书名" type="xs:string"/>
<xs:element name="作者" type="xs:string"/>
<xs:element name="售价" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Book.xml
<?xml version="1.0" encoding="UTF-8"?>
<itcast:书架 xmlns:itcast="http://www.itcast.cn"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.itcast.cn book.xsd">
<itcast:书>
<itcast:书名>JAVA 就业培训教程</itcast:书名>
<itcast:作者>张孝祥</itcast:作者>
<itcast:售价>29.00元</itcast:售价>
</itcast:书>
</itcast:书架>
例19、xml schema实例2.
Shiporder.xsd
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.itcast.cn"
elementFormDefault="qualified">
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
Shiporder.xml
<?xml version="1.0" encoding="UTF-8"?>
<shiporder xmlns="http://www.itcast.cn"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.itcast.cn shiporder.xsd"
orderid="xxx">
<orderperson>xxx</orderperson>
<shipto>
<name>xxx</name>
<address>xxx</address>
<city>xxx</city>
<country>xxx</country>
</shipto>
<item>
<title>xxx</title>
<note>bbb</note>
<quantity>123</quantity>
<price>1.9</price>
</item>
</shiporder>
例20、一道关于打印的面试题,打印如下数字:
3 7
2 4 6 8
1 5 9
像这样的题目,即为平面图形题:使用二维数组,然后将这些数字装到数组当中!
public class Demo10 {
public static void main(String[] args) {
int num=9;
int arr[][]=new int[3][9];
int x=2;
int y=0;
boolean order=false;//默认为减
for(int i=1;i<=9;i++){
arr[x][y]=i;
y++;
if(!order){
x--;
}
if(order){
x++;
}
if(x<0){
order=true;
x=x+2;
}
if(x>2){
order=false;
x=x-2;
}
}
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
if(arr[i][j]==0){
System.out.print(" ");
}
else{
System.out.print(arr[i][j]);
}
}
System.out.println();
}
}
}
另外的方法:
package fandong;
public class Demo10 {
public static void main(String[] args) {
int num=23;
int height=num/4+1;
int width=num;
int arr[][]=new int[height][width];
int x=height-1;
int y=0;
boolean order=false;//默认为减
for(int i=1;i<=num;i++){
arr[x][y]=i;
y++;
if(order==false){
x--;
}
if(order==true){
x++;
}
if(x<0){
order=true;
x=x+2;
}
if(x>height-1){
order=false;
x=x-2;
}
}
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
if(arr[i][j]==0){
System.out.print(" ");//一位数为一个空格,两位数为两个空格
}
else{
System.out.print(arr[i][j]);
}
}
System.out.println();
}
}
}