xml文件解析方式完成银行用户业务操作

1 篇文章 0 订阅


java work week-three
题目:
设计银行用户业务操作,并通过控制台完成相应的存取款、修改密码等操作(配置文件或注解方式)
例:
用户数据保存格式如下:
user.xml
<id=“2233443545454” username=”li” phone=”1234567890” mony=”60” type=”1”>
1代表储蓄用户 2代表信用卡用户

银行业务操作如下:
control.xml
<id=“getMoney” class=”com.bank.contorller.MoneyAction”>

附加题:
将用户信息使用序列化方式存取

这题需要对xml文件,以及xml文件处理方式有了解。

DocumentBuilderFactory解析XML

javax.xml.parsers包中的DocumentBuilderFactory用于创建DOM模式的解析器对象,DocumentBuilderFactory是一个抽象工厂类,它不能直接实例化,但该类提供了一个newInstance方法 ,这个方法会根据本地平台默认安装的解析器,自动创建一个工厂的对象并返回。

调用DocumentBuilderFactory.newInstance()方法得到创建DOM解析器的工厂
DocumentBuilderFactory doc = DocumentBuilderFactory.newInstance();

调用工厂对象的newDocumentBuilder方法得到DOM解析器对象
DocumentBuilder db = doc.newDocumentBuilder();

把要解析的XML文档转化为输入流,以便DOM解析器解析它
InputStream input = new FileInputStream(“xx.xml”);

得到XML文档的根节点
Element root = doc.getDocumentElement();

得到节点的子节点
NodeList users = root.getChildNodes();

user.xml和control.xml

题目中不是标准的xml文件写法…自己写文件时要写标准,否则xml工具用不了。

user.xml

<?xml version="1.0" encoding="UTF-8"?>
<users>
	<user>
		<id>1001</id>
		<password>123456</password>
		<username>zhang</username>
		<phone>13940562354</phone>
		<money>3800</money>
		<type>2</type>
	</user>
	<user>
		<id>1002</id>
		<password>654321</password>
		<username>li</username>
		<phone>13752412365</phone>
		<money>2000</money>
		<type>1</type>
	</user>
</users>

得到根节点后(上一小节),得到带有指定标签名的对象的集合
NodeList nodeList = ele.getElementsByTagName(“id”);

对集合进行循环(循环变量i),得到属性值(两对尖括号中间)
Node node = nodeList.item(i);
node.getTextContent();
(详见下面Login.java)

还有一种写法:

<?xml version="1.0" encoding="UTF-8"?>
<Users> 
  <user id="2233443545454" username="li" password="123456" phone="1234567890" money="110.0" type="1"/>  
  <user id="2233443545655" username="ming" password="234" phone="1234567890" money="60" type="1"/>  
  <user id="2233443545427" username="ha" password="345" phone="1234567890" money="70.0" type="1"/> 
</Users>

但他们用xml工具取值的方式是不同的。

control.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Controls>
	<control id="getMoney" class="MoneyAction"/>
	<control id="saveMoney" class="MoneyAction"/>
	<control id="showMoney" class="MoneyAction"/>
	<control id="changePassword" class="ChangePassword"/>
</Controls>

取属性值方式 node.getAttribute(“id”);
(详见下面Show.java)

xml文件解析方式完成银行用户业务操作

接下来是若干文件…放心复制回去运行…

User.java
首先建立用户信息类

package three;

import java.io.Serializable;
import java.util.Arrays;

// 用户信息类
public class User implements Serializable {

	private String account;
	private char[] password;
	private String userName;
	private String phone;
	private int money;
	private int type;
	
	public User(String account, char[] password, String userName, String phone, int money, int type) {
		
		super();
		this.setAccount(account);
		this.setPassword(password);
		this.setUserName(userName);
		this.setPhone(phone);
		this.setMoney(money);
		this.setType(type);
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public char[] getPassword() {
		return password;
	}

	public void setPassword(char[] password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public int getMoney() {
		return money;
	}

	public void setMoney(int money) {
		this.money = money;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}
	
	@Override
	public String toString() {
		return "User:account=" + account + ",password=" + Arrays.toString(password) + ",userName=" + userName + ",phone=" + phone + ",money=" + money + ",type=" + type;
	}
}

Login.java
这里就涉及到第一种user.xml的解析…

package three;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Login {

	private static String userXml = "src/three/user.xml";
	
	public static String init() {
		
		Scanner input = new Scanner(System.in);
		
		while(true) {
			
			System.out.println("请输入银行账号");
			String account = input.next();
			
			// 实例化DOM解析器的工厂
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder;
			Document document;
			
			User user = null;
			
			try {
				
				// 得到DOM解析器对象
				documentBuilder = builderFactory.newDocumentBuilder();
				// 解析XML文档,得到代表整个文档的 Document 象,可以利用DOM特性对整个XML文档操作
				document = documentBuilder.parse(new File(userXml));
				
				// 得到XML文档的根节点
				Element ele = document.getDocumentElement();
				// 得到带有指定标签名的对象的集合
				NodeList nodeList = ele.getElementsByTagName("id");
				
				for(int i=0; i<nodeList.getLength(); i++) {
					
					Node node = nodeList.item(i);
					String userAcc = node.getTextContent();
					
					if(userAcc.equals(account)) { // 账号存在
						
						Element father = (Element)node.getParentNode();
						// 根据名字获取标签得节点,再取值
						Node passwordNode = father.getElementsByTagName("password").item(0);
						Node usernameNode = father.getElementsByTagName("username").item(0);
						Node phoneNode = father.getElementsByTagName("phone").item(0);
						Node moneyNode = father.getElementsByTagName("money").item(0);
						Node typeNode = father.getElementsByTagName("type").item(0);
						
						char[] userPas = passwordNode.getTextContent().toCharArray();
						String userName = usernameNode.getTextContent();
						String userPho = phoneNode.getTextContent();
						int userMon = Integer.parseInt(moneyNode.getTextContent());
						int userType = Integer.parseInt(typeNode.getTextContent());
						
						user = new User(userAcc, userPas, userName, userPho, userMon, userType);
						break;
					}
				}
			} catch(ParserConfigurationException | SAXException | IOException e) {
				e.printStackTrace();
			}
			
			if(user == null) {
				System.out.println("银行账户不存在");
			} else {
				
				boolean flag = false;
				for(int i=0; i<3; i++) {
					
					System.out.println("请输入密码");
					String pas = input.next();
					if(Arrays.equals(user.getPassword(), pas.toCharArray())) {
						flag = true;
						break;
					} else {
						System.out.println("密码输入有误");
					}
				}
				
				if(flag) {
					Show.init(user);
				} else {
					System.out.println("密码输入错误超过3次");
				}
			}
		}
	}
}

WriteUser.java
对于xml中稳定的账户,只存在改密码,修改余额这两种操作,所以只需改这两个的值。

package three;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class WriteUser {

	private static String userXml = "src/three/user.xml";

	public static void write(User user) {
		
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder;
		Document document;
		
		try {
			documentBuilder = builderFactory.newDocumentBuilder();
			document = documentBuilder.parse(new File(userXml));
			
			Element ele = document.getDocumentElement();
			NodeList nodeList = ele.getElementsByTagName("id");
			
			for(int i=0; i<nodeList.getLength(); i++) {
				
				Node node = nodeList.item(i);
				String userAcc = node.getTextContent();
				System.out.println(userAcc);
				
				if(userAcc.equals(user.getAccount())) { // 账号存在
					
					Element father = (Element)node.getParentNode();
					Node passwordNode = father.getElementsByTagName("password").item(0);
					Node usernameNode = father.getElementsByTagName("username").item(0);
					Node phoneNode = father.getElementsByTagName("phone").item(0);
					Node moneyNode = father.getElementsByTagName("money").item(0);
					Node typeNode = father.getElementsByTagName("type").item(0);
					
					char[] ps = user.getPassword();
					String psStr = "";
					for(int j=0; j<ps.length; j++) {
						psStr += ps[j];
					}
					// 只有密码和余额可能发生更改
					passwordNode.setTextContent(psStr);
					moneyNode.setTextContent(String.valueOf(user.getMoney()));
					break;
				}
			}
			
			// 把DOM写回XML文件
			TransformerFactory tFactory = TransformerFactory.newInstance();
			Transformer ts = tFactory.newTransformer();
			ts.setOutputProperty(OutputKeys.INDENT, "yes");
			ts.transform(new DOMSource(ele), new StreamResult(userXml));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

MoneyAction.java

package three;

import java.util.Scanner;

public class MoneyAction {

	// 取款
	public static boolean drawMoney(User user) {
		
		Scanner input = new Scanner(System.in);
		boolean flag = true;
		System.out.print("请输入取款金额:");
		
		int money = input.nextInt();
		
		if(user.getMoney() >= money) {
			user.setMoney(user.getMoney() - money);
			System.out.println("取款成功");
		} else {
			System.out.println("取款失败");
			flag = false;
		}
		
		return flag;
	}
	
	// 存款
	public static boolean saveMoney(User user) {
		
		Scanner input = new Scanner(System.in);
		System.out.print("请输入存款金额:");
		int money = input.nextInt();
		user.setMoney(user.getMoney() + money);
		System.out.println("存款成功");
		return true;
	}
	
	public static void showMoney(User user) {
		System.out.println("账户余额:" + user.getMoney());
	}
}

ChangePassword.java

package three;

import java.util.Arrays;
import java.util.Scanner;

public class ChangePassword {

	public static void init(User user) {
		
		char[] password = user.getPassword();
		Scanner input = new Scanner(System.in);
		System.out.println("请输入旧密码");
		String oldPass = input.next();
		
		if(Arrays.equals(password, oldPass.toCharArray())) {
			
			System.out.println("请输入新密码");
			String new1 = input.next();
			
			while(new1.length() != 6) {
				System.out.println("位数有误,请输入6位数字");
				new1 = input.next();
			}
			
			System.out.println("请再次输入密码");
			String new2 = input.next();
			
			while(new2.length() != 6) {
				System.out.println("位数有误,请输入6位数字");
				new2 = input.next();
			}
			
			if(new1.equals(new2)) {
				for(int i=0; i<new1.length(); i++) {
					if(!Character.isDigit(new1.charAt(i))) {
						System.out.println("密码不为数字,修改失败");
						return;
					}
				}
			} else {
				System.out.println("两次密码输入不一致,修改失败");
				return;
			}
			
			user.setPassword(new1.toCharArray());
			System.out.println("修改成功");
		} else {
			System.out.println("密码错误");
		}
	}
}

Show.java

package three;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Show {

	private static String controlXml = "src/three/control.xml";

	public static void init(User user) {

		Scanner input = new Scanner(System.in);
		String[] options = new String[] { "getMoney", "saveMoney", "showMoney", "changePassword" };

		while (true) {

			System.out.println("请选择操作:【1】取款  【2】存款  【3】查看余额  【4】修改密码  【5】退出");

			while (true) {

				int integer = input.nextInt();
				if (integer > 0 && integer < 5) {
					control(options[integer - 1], user, integer);
					break;
				} else if (integer == 5) {
					WriteUser.write(user);
					System.exit(0);
				} else {
					System.out.println("输入有误,请重新输入!");
				}
			}
		}
	}

	public static void control(String str, User user, int type) {
		
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder;
		Document document;
		
		try {
			documentBuilder = builderFactory.newDocumentBuilder();
			document = documentBuilder.parse(new File(controlXml));
			Element ele = document.getDocumentElement();
			NodeList nodeList = ele.getElementsByTagName("control");
			
			for(int i=0; i<nodeList.getLength(); i++) {
				
				Element node = (Element)nodeList.item(i);
				if(node.getAttribute("id").equals(str)) {

					String classpath = node.getAttribute("class");
					// 读xml的class没问题
					try {
//						Class op = Class.forName(classpath);
						System.out.println("type" + type);
						switch (type) {
						case 1:
							MoneyAction.drawMoney(user);
							break;
						case 2:
							MoneyAction.saveMoney(user);
							break;
						case 3:
							MoneyAction.showMoney(user);
							break;
						default:
							ChangePassword.init(user);
						}
					} catch(Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch(ParserConfigurationException | SAXException | IOException e) {
			e.printStackTrace();
		}
	}
}

MainThree.java

package three;

public class MainThree {

	public static void main(String[] args) {
		
		Login.init();
	}
}

以及附加题…序列化

package three;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestSerializable {

	public static void main(String[] args) {
		
		String path = "src/three/user.object";
		User user = new User("1003", new char[] {'3','2','1','4','5','6'}, "wang", "13945623564", 1000, 1);
		
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
			oos.writeObject(user);
			oos.close();
			
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
			User u = (User)ois.readObject();
			ois.close();
			System.out.print(u);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

当然身为毛毛虫一只(因为我们是成蝶计划),还有很多不足…
这些也是照老师给的示例以及百度整理的…

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值