前端之家收集整理的这篇文章主要介绍了
客户端发送xml数据,服务器端接收之,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.xiuye.xml;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Server {
public static void main(String args[])
{
try{
ServerSocket server = new ServerSocket(8888);
System.out.println("listening...");
Socket socket = server.accept();
System.out.println("connected by client");
InputStream in = socket.getInputStream();
SAXReader reader = new SAXReader();
System.out.println("analyze xml from client");
Document doc = reader.read(in);
Element root = doc.getRootElement();
List<Element> elements = root.elements();
for(Element e : elements)
{
int id = Integer.parseInt(e.attributeValue("id"));
String name = e.elementText("name");
int age = Integer.parseInt(e.elementText("age"));
String geneder = e.elementText("geneder");
double salary = Double.parseDouble(e.elementText("salary"));
System.out.println(id+","+name
+","+age+","+geneder
+","+salary);
}
server.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
<pre name="code" class="java">package com.xiuye.xml;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost",8888);
OutputStream out = socket.getOutputStream();
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("EmpList.xml"));
XMLWriter writer = new XMLWriter(System.out);
writer.setOutputStream(out);
writer.write(doc);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
原文链接:https://www.f2er.com/xml/296160.html