通常可以使用在休息传输方面:
import java.io.StringReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlUtil {
/**
* 生成xml头文件
* @return
*/
private static Document constructDocument(){
Document document = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement("message");
document.setRootElement(root);
return document;
}
/**
* 构建xml
* @param username
* @return
*/
public static String construtsXml(String username){
Document document = constructDocument();
Element root = document.getRootElement();
Element type = root.addElement("type");
type.setText("1");
Element user = root.addElement("user");
user.setText(username);
return document.asXML();
}
/**
* 解析xml
* @param xml
* @return
* @throws Exception
*/
public static String analysisXml(String xml) throws Exception{
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new StringReader(xml));
Element root = document.getRootElement();
String rootName = root.getName();
Element type = root.element("type");
Element username = root.element("user");
return rootName+": type="+type.getText()+", username="+username.getText();
}
}
import java.io.StringReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlUtil {
/**
* 生成xml头文件
* @return
*/
private static Document constructDocument(){
Document document = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement("message");
document.setRootElement(root);
return document;
}
/**
* 构建xml
* @param username
* @return
*/
public static String construtsXml(String username){
Document document = constructDocument();
Element root = document.getRootElement();
Element type = root.addElement("type");
type.setText("1");
Element user = root.addElement("user");
user.setText(username);
return document.asXML();
}
/**
* 解析xml
* @param xml
* @return
* @throws Exception
*/
public static String analysisXml(String xml) throws Exception{
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new StringReader(xml));
Element root = document.getRootElement();
String rootName = root.getName();
Element type = root.element("type");
Element username = root.element("user");
return rootName+": type="+type.getText()+", username="+username.getText();
}
}