javaWeb 学习之旅(二)--------XML的使用方法
二、xml的使用方法
1.最简单的声明语法:
<?xml version="1.0"?>
常用的方法有:<?xml version="1.0" encoding="UTF-8"?>或者<?xml version="1.0" encoding="GB2312"?>
还有一个属性:说明文档是否独立 standalone="yes"
CDATA区: xml解析程序不会处理,按原样输出,语法如下: <![CDATA[内容]]>
2.DTD约束
book.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE 书架 SYSTEM "book.dtd">
<书架>
<书>
<书名> 数据结构</书名>
<作者> 某某某</作者>
</书>
<书>
<书名> 大学语文</书名>
<作者> 某某某</作者>
</书>
</书架>
book.dtd
<!ELEMENT 书架(书+)>
<!ELEMENT 书 (书名,作者)>
<!ELEMENT 书名 (#PCDATA)>
<!ELEMENT 作者 (#PCDATA)>
2.Dom和Sax解析方法的区别:
1.Dom 解析的优点,对文档的增、删、改、查、比较方便,缺点占用的内存较大
2.Sax解析的优点是占用内存少, 解析速度快,缺点是只适合做文档的读取,不适合做文档的增、删、改、查、
3.调整JVM的大小
JVM默认的是64M的内存,超过之后,后抛出异常
配置JVM的大小如下: run as --Open Run Dialog -----------Argument----- VM argument 中输入 -Xmx90m 这样就可以配置90M的内存
4.XML解析技术
XML的解析开发包如下: Jaxp(Sun) Jdom dom4j
1.DOM解析步骤:
// 1.创建工厂
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
// 2.得到dom解析器
DocumentBuilder builder=factory.newDocumentBuilder();
// 3.解析xml文档,得到代表文档的document
Document document=builder.parse("src/test.xml");
更新后的内容重新写入XML文档中
// 更新后的内容写会XML文档中
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(
new FileOutputStream("src/test.xml")));
XML中的一些方法
获取属性的
// 得到根节点
Element element = (Element) document.getElementsByTagName("书名").item(0);
String value = element.getAttribute("name");
System.out.println(value);
在指定位置增加节点元素
// 创建节点
Element print = document.createElement("出版社");
print.setTextContent("南阳理工学院");
//注意一下:这里的“作者”是在xml文档中从“0”开始算起 出现的第几次,
Element bookElement = (Element) document.getElementsByTagName("作者")
.item(1);
//注意一下:这里的“书”是在xml文档中从“0”开始算起 出现的第几次,
Element rootElement = (Element) document.getElementsByTagName("书")
.item(1);
rootElement.insertBefore(print, bookElement);
指定位置增加属性
Element bookname = (Element) document.getElementsByTagName("书名")
.item(1);
bookname.setAttribute("name", "book");
删除节点元素
//注意一下:这里的“作者”是在xml文档中从“0”开始算起 出现的第几次,
Element deleteElement = (Element) document.getElementsByTagName("作者")
.item(3);
//注意一下:这里的“书”是在xml文档中从“0”开始算起 出现的第几次,
Element rootElement = (Element) document.getElementsByTagName("书")
.item(3);
//这个方法是删除所在元素的节点
// deleteElement.getParentNode().getParentNode().removeChild(deleteElement.getParentNode());
rootElement.removeChild(deleteElement);
更新节点元素内容
//注意一下:这里的“作者”是在xml文档中从“0”开始算起 出现的第几次,
Element updateElement = (Element) document.getElementsByTagName("作者")
.item(3);
updateElement.setTextContent("wangjie");
2.例子 用java实现的学生成绩系统,实现对XML文件进行增、删、改、查
实现的过程如下:
XmlUtils.java 有得到XML文档的方法和保存更新后XML文档的方法
public class XmlUtils {
//有得到XML文档的方法
private static String filename = "src/exam.xml";
public static Document getdDocument() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
return builder.parse(filename);
}
//保存更新后XML文档的方法
public static void write2Xml(Document document) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(
new FileOutputStream(filename)));
}
}
Student.java 是用来保存 javabean 的Get和Set的方法
public class Student {
private String id;
private String examid;
private String name;
private String location;
private double grade;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
}
然后是实现增、删、改、查的模块StudentDao.java
package com.nyist.student.Dao;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.jar.Attributes.Name;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.nyist.Exception.StudentNotException;
import com.nyist.XmlUtils.XmlUtils;
import com.nyist.student.bean.Student;
public class StudentDao {
@Test
public void add(Student student) {
try {
Document document = XmlUtils.getdDocument();
// 创建出封装学生信息的标签
Element student_tag = document.createElement("student");
student_tag.setAttribute("id", student.getId());
student_tag.setAttribute("examid", student.getExamid());
// 创建用于封装学生姓名所在地、成绩的标签
Element name = document.createElement("name");
Element location = document.createElement("location");
Element grade = document.createElement("grade");
name.setTextContent(student.getName());
location.setTextContent(student.getLocation());
grade.setTextContent(student.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) {
}
}
public Student find(String examid) {
Student student = new Student();
try {
Document document = XmlUtils.getdDocument();
NodeList list = document.getElementsByTagName("student");
for (int i = 0; i < list.getLength(); i++) {
Element student_tagElement = (Element) list.item(i);
if (student_tagElement.getAttribute("examid").equals(examid)) {
student.setExamid(examid);
student.setId(student_tagElement.getAttribute("id"));
student.setName(student_tagElement
.getElementsByTagName("name").item(0)
.getTextContent());
student.setLocation(student_tagElement
.getElementsByTagName("location").item(0)
.getTextContent());
student.setGrade(Double.parseDouble(student_tagElement
.getElementsByTagName("grade").item(0)
.getTextContent()));
System.out.println("准考证号:" + student.getExamid() + "\n"
+ "姓名:" + student.getName() + "\n" + "学号:"
+ student.getId() + "\n" + "所在地:"
+ student.getLocation() + "\n" + "成绩:"
+ student.getGrade());
return student;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
return null;
}
public void delete(String name) throws StudentNotException {
try {
Document document = XmlUtils.getdDocument();
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 StudentNotException(name + "该学生信息不存在!!");
} catch (StudentNotException e) {
// TODO Auto-generated catch block
throw e;
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
}
最后是主界面,实现增删改查的交互功能main.java
package com.nyist.ui;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.nyist.student.Dao.StudentDao;
import com.nyist.student.bean.Student;
public class main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("添加学生(a) 删除学生(b) 查找学生(c) 修改(d) ");
System.out.print("请输入操作类型");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(System.in));
String type = bufferedReader.readLine();
// 增加学生信息的操作
if ("a".equals(type)) {
System.out.print("请输入学生的姓名");
String name = bufferedReader.readLine();
System.out.print("请输入学生的ID");
String id = bufferedReader.readLine();
System.out.print("请输入学生的准考证号");
String examid = bufferedReader.readLine();
System.out.print("请输入学生的所在地");
String location = bufferedReader.readLine();
System.out.print("请输入学生的成绩");
String grade = bufferedReader.readLine();
Student student = new Student();
student.setExamid(examid);
student.setId(id);
student.setLocation(location);
student.setName(name);
student.setGrade(Double.parseDouble(grade));
StudentDao dao = new StudentDao();
dao.add(student);
System.out.println("添加成功!!");
}
// 删除学生信息的操作
else if ("b".equals(type)) {
System.out.println("请输入要删除学生的姓名");
String name = bufferedReader.readLine();
try {
StudentDao dao = new StudentDao();
dao.delete(name);
System.out.println("删除成功!!");
} catch (Exception e) {
// TODO: handle exception
System.out.println("你要删除的学生不存在!!");
}
}
// 查找学生信息的操作
else if ("c".equals(type)) {
System.out.println("请输入要查找学生的准考证号");
String examid = bufferedReader.readLine();
try {
StudentDao dao = new StudentDao();
dao.find(examid);
System.out.println("查找成功!!");
} catch (Exception e) {
// TODO: handle exception
System.out.println("你要查找的学生不存在!!");
}
}
// 删除学生信息的操作
else if ("d".equals(type)) {
System.out.println("请输入要更新学生的姓名");
String name = bufferedReader.readLine();
try {
StudentDao dao = new StudentDao();
dao.delete(name);
System.out.print("请输入学生的ID");
String id = bufferedReader.readLine();
System.out.print("请输入学生的准考证号");
String examid = bufferedReader.readLine();
System.out.print("请输入学生的所在地");
String location = bufferedReader.readLine();
System.out.print("请输入学生的成绩");
String grade = bufferedReader.readLine();
Student student = new Student();
student.setExamid(examid);
student.setId(id);
student.setLocation(location);
student.setName(name);
student.setGrade(Double.parseDouble(grade));
dao.add(student);
System.out.println("更新成功!!");
} catch (Exception e) {
// TODO: handle exception
System.out.println("你要更新的学生不存在!!");
}
}
else {
System.out.println("不支持这个操作!!");
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("亲,出错了");
}
}
}
其中用到一个异常的处理类 StudentNotException.java 是继承了exception的方法
package com.nyist.Exception;
public class StudentNotException extends Exception {
public StudentNotException() {
// TODO Auto-generated constructor stub
}
public StudentNotException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public StudentNotException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public StudentNotException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
保存数据的XML文件如下:exam.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<exam>
<student examid="100" id="001">
<name>张三</name>
<location>南阳</location>
<grade>22</grade>
</student>
<student examid="101" id="002">
<name>王某某</name>
<location>南阳</location>
<grade>21</grade>
</student>
<student examid="102" id="003">
<name>李某某</name>
<location>南阳</location>
<grade>23</grade>
</student>
<student examid="111" id="111">
<name>wangjie</name>
<location>111</location>
<grade>111.0</grade>
</student>
</exam>
工程包下载地址:http://download.csdn.net/detail/wjky2014/5220366
3.SAX解析XML技术
// 1.创建解析工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
// 2.得到解析器
SAXParser saxParser = factory.newSAXParser();
// 3.得到读取器
XMLReader reader = saxParser.getXMLReader();
// 4.设置内容处理器
beanListHandler handler = new beanListHandler();
reader.setContentHandler(handler);
// 5.读取xml文档的内容
reader.parse("src/test.xml");
List<Book> list = handler.getbooks();
System.out.println(list);
// 把XML文档中的每一本书封装的一个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 ("书".equals(currenttag)) {
book = new Book();
}
}
@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);
System.out.println(name);
}
if ("作者".equals(currenttag)) {
String author = new String(ch, start, length);
book.setAuthor(author);
System.out.println(author);
}
if ("售价".equals(currenttag)) {
String prize = new String(ch, start, length);
book.setPrize(prize);
System.out.println(prize);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("书")) {
list.add(book);
book = null;
}
currenttag = null;
}
// 得到list集合
public List getbooks() {
return list;
}
用javabean的方法封装XML文档类的Book.java
package com.nyist.sax;
public class Book {
private String name;
private String author;
private String prize;
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 getPrize() {
return prize;
}
public void setPrize(String prize) {
this.prize = prize;
}
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<书架>
<书>
<书名>android 开发</书名>
<作者>王宇</作者>
<售价>32元</售价>
</书>
<书>
<书名 > 数据结构</书名>
<作者>王小米</作者>
<售价>40元</售价>
</书>
<书>
<书名 > 大学英语</书名>
<作者>王大米</作者>
<售价>50元</售价>
</书>
</书架>
4.Dom4j 实现对xml 文件的增、删、改、查、的功能
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/test.xml"));
2.实现增、删、查、改的功能
Element book = (Element) document.getRootElement().elements("书").get(2);
List list = book.elements();
Element location = DocumentHelper.createElement("出版社");
location.setText("人民日报出版社");
list.add(location)
Element book = (Element) document.getRootElement().elements("书").get(2);
book.getParent().remove(book);
更新一节点的方法
Element book = (Element) document.getRootElement().elements("书").get(1);
book.element("出版社").setText("南阳理工学院");
@Test
// 得到xml文档的内容
public void read() throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/test.xml"));
Element root = document.getRootElement();
Element book = (Element) root.elements().get(1);
String value = book.element("书名").getText();
System.out.println(value);
}
@Test
// 得到xml文档的的属性
public void readAttr() throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/test.xml"));
Element root = document.getRootElement();
Element book = (Element) root.elements().get(1);
String value = book.element("书名").attributeValue("name");
System.out.println(value);
}
@Test
public void add() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/test.xml"));
Element book = (Element) document.getRootElement().elements("书").get(1);
book.addElement("出版社").setText("人民日报出版社");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
// 第一种方法
// XMLWriter writer=new XMLWriter(new OutputStreamWriter(new
// FileOutputStream("src/test.xml"), "UTF-8"));
// 第二种方法
XMLWriter writer = new XMLWriter(new FileOutputStream("src/test.xml"),
format);
writer.write(document);
writer.close();
}
// 在制定位置添加
@Test
public void add2() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/test.xml"));
Element book = (Element) document.getRootElement().elements("书").get(2);
List list = book.elements();
Element location = DocumentHelper.createElement("出版社");
location.setText("人民日报出版社");
list.add(location);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
// 第一种方法
// XMLWriter writer=new XMLWriter(new OutputStreamWriter(new
// FileOutputStream("src/test.xml"), "UTF-8"));
// 第二种方法
XMLWriter writer = new XMLWriter(new FileOutputStream("src/test.xml"),
format);
writer.write(document);
writer.close();
}
// 删除添加的节点
@Test
public void delete() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/test.xml"));
Element book = (Element) document.getRootElement().elements("书").get(2);
book.getParent().remove(book);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
// 第一种方法
// XMLWriter writer=new XMLWriter(new OutputStreamWriter(new
// FileOutputStream("src/test.xml"), "UTF-8"));
// 第二种方法
XMLWriter writer = new XMLWriter(new FileOutputStream("src/test.xml"),
format);
writer.write(document);
writer.close();
}
// 更新节点
@Test
public void update() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/test.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/test.xml"), "UTF-8"));
// 第二种方法
XMLWriter writer = new XMLWriter(new FileOutputStream("src/test.xml"),
format);
writer.write(document);
writer.close();
}
5.用Xpath提取XML文档的数据
/**
* 查找user.xml 文档是否有用户相匹配的用户名和密码
*
* @throws DocumentException
*
*/
public static void main(String[] args) throws DocumentException {
// TODO Auto-generated method stub
String username = "wangjie";
String password = "123456";
// 检测XML文档中是否有匹配的用户名和密码
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/user.xml"));
Node node = document.selectSingleNode("//user[@username='" + username
+ "'and @password='" + password + "']");
if (node == null) {
System.out.println("用户名和密码错误!!");
} else {
System.out.println("登陆成功!!");
}
}
user.xml文件如下
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="1" username="wangjie" password="123456" email="1150580768@qq.com" />
<user id="2" username="wang" password="123456" email="1150580768@qq.com" />
</users>
6. XML Schema
5.打印图形M
/**
* 打印 M
* 这样的东西都是平面图形题
* 可以使用二维数组解决问题
*
* 3 7
* 2 4 6 8
* 1 5 9
*
* **/
public static void main(String[] args) {
int num = 13;
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();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!