1 Star 0 Fork 0

曾铖坚 / day24-code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
dom4jDemo2.java 3.10 KB
一键复制 编辑 原始数据 按行查看 历史
曾铖坚 提交于 2024-04-17 18:57 . java中解析XML文件2
package com.itheima.a03dom4jdemo;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class dom4jDemo2 {
public static void main(String[] args) throws DocumentException {
ArrayList<User> list = new ArrayList<>();
//1.创建一个解析器对象
SAXReader saxReader = new SAXReader();
//2.对xml文件进行解析,并得到文档对象
File file = new File("sockethomework\\src\\com\\itheima\\a03dom4jdemo\\users.xml");
Document document = saxReader.read(file);
//3.一层一层扒开得到xml文件里面的内容,先获得根标签
Element rootElement = document.getRootElement();
//4.获得根标签中的用户标签
List<Element> elements = rootElement.elements();
for (Element element : elements) {
//属性id
Attribute id = element.attribute("id");
String idValue = id.getText();
//用户名
Element username = element.element("username");
String usernameValue = username.getText();
//密码
Element password = element.element("password");
String passwordValue = password.getText();
//身份证
Element personid = element.element("personid");
String personidValue = personid.getText();
//电话号码
Element phoneid = element.element("phoneid");
String phoneidValue = phoneid.getText();
//是否是管理员
Element flag = element.element("flag");
String flagdValue = flag.getText();
boolean b = Boolean.parseBoolean(flagdValue);
//创建用户对象
User user = new User(idValue, usernameValue, passwordValue, personidValue, phoneidValue, b);
list.add(user);
}
//打印集合
System.out.println(list);
//登录操作
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String usernameInput = sc.nextLine();
System.out.println("请输入密码:");
String passwordInput = sc.nextLine();
int index = getIndex(list, usernameInput);
if (index >= 0) {
//表示用户名存在,接下来判断密码
if (list.get(index).getPassword().equals(passwordInput)){
System.out.println("登录成功");
}else {
System.out.println("密码输入错误!");
}
} else {
//表示用户名不存在
System.out.println("用户名未注册!");
}
}
//判断用户名是否存在
public static int getIndex(ArrayList<User> list, String username) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getUsername().equals(username)) {
return i;
}
}
//不存在返回-1
return -1;
}
}
1
https://gitee.com/zeng-chengjian/day24-code.git
git@gitee.com:zeng-chengjian/day24-code.git
zeng-chengjian
day24-code
day24-code
master

搜索帮助