高级编程--XML+socket练习题

<?xml version="1.0" encoding="GBK"?>

<citys>

<city id='010'>

<cityname>北京</cityname>

<cityarea>华北</cityarea>

<population>2114.8万人</population>

</city>

<city id='021'>

<cityname>上海</cityname>

<cityarea>华东</cityarea>

<population>2,500万人</population>

</city>

<city id='020'>

<cityname>广州</cityname>

<cityarea>华南</cityarea>

<population>1292.68万人</population>

</city>

<city id='028'>

<cityname>成都</cityname>

<cityarea>华西</cityarea>

<population>1417万人</population>

</city>

</citys>

(1)使用dom4j将信息存入xml中

(2)读取信息,并打印控制台

(3)添加一个city节点与子节点

(4)使用socket TCP协议编写服务端与客户端,

客户端输入城市ID,服务器响应相应城市信息

(5)使用socket TCP协议编写服务端与客户端,客户端要求用户输入city对象,服务端接收并使用dom4j保存至XML文件

(1)(2)(3)

Manager

复制代码
package homework01;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/9/12 14:03
 * @Version: 1.0
 */

public class Manager {
    public Document document;
    public Manager() throws DocumentException {}
    //创建文件 并写入信息
    public void createxml(String filepath) throws IOException {
        document = DocumentHelper.createDocument();
        Element rootElement = document.addElement("citys");

        addInfo(rootElement,"010","北京","华北","2114.8万人");
        addInfo(rootElement,"021","上海","华东","2500万人");
        addInfo(rootElement,"028","南京","华西","1417万人");

        //写入
        OutputFormat output = new OutputFormat();
        XMLWriter writer = new XMLWriter(new FileWriter(filepath),output);
        writer.write(document);
        writer.close();
    }
    //写入信息
    public void addInfo(Element root,String id,String cityname,String cityarea,String population){
        Element city = root.addElement("city");
        city.addAttribute("id",id);
        city.addElement("cityname").addText(cityname);
        city.addElement("cityarea").addText(cityarea);
        city.addElement("population").addText(population);
    }
    //读取信息并打印
    public void readXML(String filepath) throws DocumentException {
        //创建编译器
        SAXReader saxReader = new SAXReader();
        document = saxReader.read(filepath);

        Element rootElement = document.getRootElement();
        List<Element> citys = rootElement.elements();
        for (Element city : citys){
            System.out.println("--------------------------");
            System.out.println("城市id:" + city.attributeValue("id"));
            System.out.println("城市名称:" + city.elementText("cityname"));
            System.out.println("城市区域:" + city.elementText("cityarea"));
            System.out.println("城市人口:" + city.elementText("population"));
        }
    }

    //添加city节点与子节点
    //添加city节点
    public void addcity(String filepath,String id,String cityname,String cityarea,String population) throws DocumentException, IOException {
        SAXReader saxReader = new SAXReader();
        document = saxReader.read(filepath);

        Element rootElement = document.getRootElement();
        addInfo(rootElement,id,cityname,cityarea,population);

        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter(filepath), format);
        writer.write(document);
        writer.close();
    }

    public String findCityById(String filepath,String id) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        document = saxReader.read(filepath);

        Element rootElement = document.getRootElement();
        List<Element> citys = rootElement.elements();

        for (Element el : citys){
            if (el.attributeValue("id").equals(id)){
                return "城市id:" + el.attributeValue("id") + "\t城市名称:" + el.elementText("cityname") + "\t城市区域:" + el.elementText("cityarea")
                        + "\t城市人口:" + el.elementText("population");
            }
        }
        return "没有找到";
    }

}

Test

复制代码
package homework01;

import homework01.Manager;
import org.dom4j.DocumentException;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/9/12 12:02
 * @Version: 1.0
 */

public class Test {
    public static void main(String[] args) {
        try {
            Manager manager = new Manager();
            manager.createxml("./src/homework01/1.xml");

            manager.addcity("./src/homework01/1.xml","100","河南","华中","9936.6万人");

            manager.readXML("./src/homework01/1.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

(4)(5)

cityServer

复制代码
package homework01;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/9/12 17:17
 * @Version: 1.0
 */

public class cityServer {
    public static void main(String[] args) {

        try {
            Manager manager = new Manager();
            ServerSocket serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动,监听端口为8088");
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功");
            do{
                InputStream is = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                PrintWriter output = new PrintWriter(socket.getOutputStream(),true);
                String select = br.readLine();
//                System.out.println(select);


                if ("0".equals(select)){
                    break;
                }
                System.out.println(select);
                //根据id查信息
                if ("1".equals(select)){
                    String clientId = br.readLine();
                    System.out.println(clientId);
                    String cityInfo = manager.findCityById("./src/homework01/1.xml",clientId);
                    output.println(cityInfo);
                }


                //添加信息
                if ("2".equals(select)){
                    String clientId = br.readLine();
                    String cityname = br.readLine();
                    String cityarea = br.readLine();
                    String population = br.readLine();
                    manager.addcity("./src/homework01/1.xml",clientId,cityname,cityarea,population);
                    output.println("添加成功");
                }


            }while(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

cityClient

复制代码
package homework01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/9/12 17:17
 * @Version: 1.0
 */

public class cityClient {
    public static void main(String[] args) throws IOException {
        String host = "localhost";
        int port = 8088;
        Socket socket = new Socket(host, port);

        try {
            do{
                PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

                System.out.println("请输入您要选择的操作:1、查看城市信息   2、添加城市  0、退出");
                String select = reader.readLine();
                output.println(select);
                if ("0".equals(select)){
                    socket.close();
                    break;
                }
                if ("1".equals(select)){
                    System.out.println("请输入城市ID");
                    String clientId = reader.readLine();
                    output.println(clientId);
                }

                if ("2".equals(select)){
                    System.out.println("请输入城市ID");
                    String clientId = reader.readLine();
                    System.out.println("请输入城市信息:");
                    System.out.println("城市名称:");
                    String cityname = reader.readLine();
                    System.out.println("城市区域:");
                    String cityarea = reader.readLine();
                    System.out.println("城市人口:");
                    String population = reader.readLine();
                    output.println(clientId);
                    output.println(cityname);
                    output.println(cityarea);
                    output.println(population);

                }


                String serverResponse = input.readLine();
//                while (serverResponse != null){
                    System.out.println("Server response: " + serverResponse);
//                }

            }while(true);


        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
相关推荐
飞剑神2 分钟前
qt svg缺失元素, 原因是不支持 rgba
开发语言·qt
Seven9710 分钟前
剑指offer-22、从上往下打印⼆叉树
java
A尘埃27 分钟前
企业级Java项目金融应用领域——保险系统(补充)
java·金融·保险系统
诗书画唱32 分钟前
【前端面试题】JavaScript 核心知识点解析(第二十二题到第六十一题)
开发语言·前端·javascript
冬天vs不冷32 分钟前
Java基础(九):Object核心类深度剖析
java·开发语言·python
TS的美梦33 分钟前
【1:1复刻R版】python版火山图函数一键出图
开发语言·python·r语言·scanpy·火山图
悟空聊架构1 小时前
我的网站被攻击了,被干掉了 120G 流量,还在持续攻击中...
java·前端·架构
陈天伟教授1 小时前
(二)Python + 地球信息科学与技术 (GeoICT)=?
开发语言·python
Dajiaonew2 小时前
Spring AI RAG 检索增强 应用
java·人工智能·spring·ai·langchain
IT古董5 小时前
第四章:大模型(LLM)】06.langchain原理-(3)LangChain Prompt 用法
java·人工智能·python