由于在学习xml的解析,闲着没事干,就练习一下DOM对xml文件的增删改查,所以就出现了该《xml版的通讯录信息管理系统1.0》
目录结构:
源码:
stuInfo.xml
<?xml version="1.0" encoding="UTF-8"?> <addresslist> <people> <name>小风</name> <sex>女</sex> <qq>56986259</qq> <age>33</age> <address>中国天津</address> <phone>15856951146</phone> </people> <people> <name>莉莉</name> <sex>女</sex> <qq>233453454</qq> <age>33</age> <address>上海</address> <phone>15395101737</phone> </people> <people> <name>张三</name> <sex>男</sex> <qq>454688112</qq> <age>22</age> <address>上海</address> <phone>18255173798</phone> </people> <people> <name>李四</name> <sex>男</sex> <qq>455555</qq> <age>16</age> <address>未知</address> <phone>18355166330</phone> </people> <people> <name>小红</name> <sex>男</sex> <qq>458954</qq> <age>99</age> <address>未知</address> <phone>15395102086</phone> </people> <people> <name>小明</name> <sex>男</sex> <qq>498651978</qq> <age>22</age> <address>安徽合肥</address> <phone>15395073025</phone> </people> </addresslist>
AddressList.java
package com.ifly.classpractice.day7_31.addressList; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileOutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; 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 AddressList extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JButton addRecord = new JButton("添 加"); private JButton lookup = new JButton("查 找"); private JButton delete = new JButton("刪 除"); private JButton showAllResult = new JButton("所 有"); private JButton change = new JButton("修 改"); private JButton reset = new JButton("清 零"); private JTextField qq = new JTextField(8); // 构造一个具有指定列数的新的空 TextField。 private JTextField name = new JTextField(8); private Object[] sex = { "男","女" }; private JComboBox gender = new JComboBox(sex); private JTextField age = new JTextField(8); private JTextField address = new JTextField(15); private JTextField phone = new JTextField(10); private Object[] columnNames = { "姓名","性别","QQ","年龄","地址","联系电话" }; private Object[][] studentInfo = new Object[53][6]; // 初始化表格的行数和列数 private JTable table = new JTable(studentInfo,columnNames); private Document doc; private File xmlFile = null; public static void main(String[] args) { new AddressList(); } public AddressList() { this.setSize(720,650); this.setTitle("通讯录"); this.setVisible(true); // 设置可见 // 设置窗口的大小是否可被改变 this.setResizable(false); this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); // 退出应用程序后的默认窗口关闭操作。 // 将窗体居中显示 double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth(); double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight(); this.setLocation((int) (width - this.getWidth()) / 2,(int) (height - this.getHeight()) / 2); // 将文本域加边框 qq.setBorder(BorderFactory.createTitledBorder("QQ")); name.setBorder(BorderFactory.createTitledBorder("姓名")); gender.setBorder(BorderFactory.createTitledBorder("性别")); age.setBorder(BorderFactory.createTitledBorder("年龄")); address.setBorder(BorderFactory.createTitledBorder("地址")); phone.setBorder(BorderFactory.createTitledBorder("电话号码")); Container con1 = getContentPane(); con1.setLayout(new FlowLayout()); // 创建一个流式布局 con1.add(name); con1.add(gender); con1.add(age); con1.add(qq); con1.add(address); con1.add(phone); Container con2 = getContentPane(); con2.setLayout(new FlowLayout()); con2.add(lookup); con2.add(delete); con2.add(showAllResult); con2.add(addRecord); con2.add(change); con2.add(reset); Container con3 = getContentPane(); JScrollPane js = new JScrollPane(table); con3.add(js); this.validate(); // 显示上面的三个容器 init(); // 初始化表格 addRecord.addActionListener(this); lookup.addActionListener(this); delete.addActionListener(this); showAllResult.addActionListener(this); change.addActionListener(this); reset.addActionListener(this); // 在发生操作事件时,调用该对象的 actionPerformed 方法。 // 为表格添加单击事件 匿名类实现 table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // System.out.println(table.getSelectedRow()); name.setText((String) studentInfo[table.getSelectedRow()][0]); if (((String) studentInfo[table.getSelectedRow()][1]) .equals("男")) {// 判断是男还是女 gender.setSelectedIndex(0); } else { gender.setSelectedIndex(1); } qq.setText((String) studentInfo[table.getSelectedRow()][2]); age.setText((String) studentInfo[table.getSelectedRow()][3]); address.setText((String) studentInfo[table.getSelectedRow()][4]); phone.setText((String) studentInfo[table.getSelectedRow()][5]); } }); } /** * 加载xml 文档对象模型 * * @return * @throws Exception */ public Document getDocument() throws Exception { // 加载xml xmlFile = new File( "src/com/ifly/classpractice/day7_31/addressList/stuInfo.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); return doc; } /** * 初始化表格 */ public void init() { for (int i = 0; i < table.getRowCount(); i++) { studentInfo[i][0] = ""; studentInfo[i][1] = ""; studentInfo[i][2] = ""; studentInfo[i][3] = ""; studentInfo[i][4] = ""; studentInfo[i][5] = ""; } try { doc = getDocument(); Element root = doc.getDocumentElement(); NodeList names = root.getElementsByTagName("name"); NodeList sexes = root.getElementsByTagName("sex"); NodeList qqs = root.getElementsByTagName("qq"); NodeList ages = root.getElementsByTagName("age"); NodeList addresses = root.getElementsByTagName("address"); NodeList phones = root.getElementsByTagName("phone"); for (int i = 0; i < names.getLength(); i++) { studentInfo[i][0] = names.item(i).getTextContent(); studentInfo[i][1] = sexes.item(i).getTextContent(); studentInfo[i][2] = qqs.item(i).getTextContent(); studentInfo[i][3] = ages.item(i).getTextContent(); studentInfo[i][4] = addresses.item(i).getTextContent(); studentInfo[i][5] = phones.item(i).getTextContent(); } // Component类的方法, 重绘此组件 repaint(); } catch (Exception e) { e.printStackTrace(); } } /* * 年龄,qq,电话 */ public boolean check(String str,String regex) { Pattern pat = Pattern.compile(regex); Matcher mat = pat.matcher(str); if (mat.matches()) { return true; } return false; } @Override public void actionPerformed(ActionEvent e) { if (addRecord == e.getSource()) { // 验证 if (name.getText().equals("")) { JOptionPane.showMessageDialog(null,"请填写姓名!","添加",JOptionPane.WARNING_MESSAGE); return; } if (!check(age.getText().trim(),"^1[6-9]$|^[2-9][0-9]$")) { JOptionPane.showMessageDialog(null,"请填写正确的年龄(16~99)!",JOptionPane.WARNING_MESSAGE); return; } if (!check(qq.getText().trim(),"^[1-9][0-9]{4,}$")) { JOptionPane.showMessageDialog(null,"请填写正确的QQ!",JOptionPane.WARNING_MESSAGE); return; } if (!check(phone.getText().trim(),"^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$")) { JOptionPane.showMessageDialog(null,"请填写正确的手机号!",JOptionPane.WARNING_MESSAGE); return; } String n = "",s = "",q = "",a = "",ad = "",p = ""; try { n = name.getText(); } catch (Exception e2) { n = ""; } try { s = (String) (gender.getSelectedItem()); } catch (Exception e3) { s = ""; } try { q = qq.getText(); } catch (Exception e4) { q = ""; } try { a = age.getText(); } catch (Exception e5) { a = ""; } try { ad = address.getText(); } catch (Exception e6) { ad = ""; } try { p = phone.getText(); } catch (Exception e7) { p = ""; } try { Node root = doc.getFirstChild(); // 得到根节点 // System.out.println(root.getNodeName()); // 创建一个新节点,并将该节点加入到root根节点后面 root.appendChild(createStudentNode(doc,n,s,q,a,ad,p)); // 对新加的信息进行保存操作 TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(new DOMSource(root),new StreamResult( new FileOutputStream(xmlFile))); // 重新加载表格 JOptionPane.showMessageDialog(null,"添加成功",JOptionPane.INFORMATION_MESSAGE); init(); resetFiled(); } catch (Exception e8) { e8.printStackTrace(); } } if (delete == e.getSource()) { if (name.getText().equals("")) { JOptionPane.showMessageDialog(null,"请选择一行!","删除",JOptionPane.WARNING_MESSAGE); return; } try { // System.out.println(table.getSelectedRow()); Element root = doc.getDocumentElement(); // 这边模拟删除,我设置性别这项不可能为空,所以利用性别来找到其父元素,根据父元素来删除 root.removeChild(root.getElementsByTagName("sex") .item(table.getSelectedRow()).getParentNode()); TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(new DOMSource(root),new StreamResult( new FileOutputStream(xmlFile))); JOptionPane.showMessageDialog(null,"删除成功",JOptionPane.INFORMATION_MESSAGE); // 将文本框清空 resetFiled(); // 重新初始化表格 init(); } catch (Exception e9) { e9.printStackTrace(); } } if (lookup == e.getSource()) { // 简单的只提供根据姓名查找 String lookupName = name.getText(); try { for (int i = 0; i < table.getRowCount(); i++) { studentInfo[i][0] = ""; studentInfo[i][1] = ""; studentInfo[i][2] = ""; studentInfo[i][3] = ""; studentInfo[i][4] = ""; studentInfo[i][5] = ""; } doc = getDocument(); Element root = doc.getDocumentElement(); NodeList names = root.getElementsByTagName("name"); NodeList sexes = root.getElementsByTagName("sex"); NodeList qqs = root.getElementsByTagName("qq"); NodeList ages = root.getElementsByTagName("age"); NodeList addresses = root.getElementsByTagName("address"); NodeList phones = root.getElementsByTagName("phone"); int index = 0; for (int i = 0; i < names.getLength(); i++) { if (names.item(i).getTextContent().equals(lookupName)) { studentInfo[index][0] = names.item(i).getTextContent(); studentInfo[index][1] = sexes.item(i).getTextContent(); studentInfo[index][2] = qqs.item(i).getTextContent(); studentInfo[index][3] = ages.item(i).getTextContent(); studentInfo[index][4] = addresses.item(i) .getTextContent(); studentInfo[index][5] = phones.item(i).getTextContent(); index++; } } repaint(); } catch (Exception e8) { e8.printStackTrace(); } } if (showAllResult == e.getSource()) { init(); } if (change == e.getSource()) { String n = "",p = ""; if (name.getText().equals("")) { JOptionPane.showMessageDialog(null,"修改",JOptionPane.WARNING_MESSAGE); return; } try { n = name.getText(); } catch (Exception e2) { n = ""; } try { s = (String) (gender.getSelectedItem()); } catch (Exception e3) { s = ""; } try { q = qq.getText(); } catch (Exception e4) { q = ""; } try { a = age.getText(); } catch (Exception e5) { a = ""; } try { ad = address.getText(); } catch (Exception e6) { ad = ""; } try { p = phone.getText(); } catch (Exception e7) { p = ""; } try { Element root = doc.getDocumentElement(); // 替换节点 root.replaceChild( createStudentNode(doc,p),root.getElementsByTagName("sex") .item(table.getSelectedRow()).getParentNode()); TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(new DOMSource(root),"修改成功",JOptionPane.INFORMATION_MESSAGE); init(); } catch (Exception e8) { e8.printStackTrace(); } } if (reset == e.getSource()) { resetFiled(); } } /** * 清空文本框 */ public void resetFiled() { qq.setText(""); name.setText(""); phone.setText(""); age.setText(""); address.setText(""); table.clearSelection(); } /** * * @param doc * @param n * @param s * @param q * @param a * @param ad * @param p * @return */ public Node createStudentNode(Document doc,String n,String s,String q,String a,String ad,String p) { Element people2 = doc.createElement("people"); try { Element name2 = doc.createElement("name"); Element sex2 = doc.createElement("sex"); Element qq2 = doc.createElement("qq"); Element age2 = doc.createElement("age"); Element address2 = doc.createElement("address"); Element phone2 = doc.createElement("phone"); name2.setTextContent(n); sex2.setTextContent(s); qq2.setTextContent(q); age2.setTextContent(a); address2.setTextContent(ad); phone2.setTextContent(p); people2.appendChild(name2); people2.appendChild(sex2); people2.appendChild(qq2); people2.appendChild(age2); people2.appendChild(address2); people2.appendChild(phone2); } catch (Exception e) { e.printStackTrace(); } return people2; } }