1.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<name>steve</name>
<sex>m</sex>
<age>30</age>
</employee>
</employees>
2.java interface
/**
* @author huangjing
* @date 2014-2-13
* 定义XML文档建立与解析的接口
*/
public interface XmlDocument {
/** * 建立XML文档 * @param fileName 文件全路径名称 */
public void createXml(String fileName); /** * 解析XML文档 * @param fileName 文件全路径名称 */
public void parserXml(String fileName); /***
* 解析短信发送返回的xml信息,封装成map.
* @param sms
* @return
*/
public Map parserSmsXml(String sms);
}
3.java implements
/**
* @author huangjing
* @date 2014-2-13
*/
public class Dom4j implements XmlDocument { @Override
public void createXml(String fileName) {
Document document = DocumentHelper.createDocument();
Element employees = document.addElement("employees");
Element employee = employees.addElement("employee");
Element name = employee.addElement("name");
name.setText("dddvip");
Element sex = employee.addElement("sex");
sex.setText("f");
Element age = employee.addElement("age");
age.setText("29");
try {
/** 格式化输出,类型IE浏览一样 */
OutputFormat format = OutputFormat.createPrettyPrint(); Writer fileWriter = new FileWriter(fileName);
XMLWriter xmlWriter = new XMLWriter(fileWriter,format);
xmlWriter.write(document);
xmlWriter.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
} @Override
public void parserXml(String fileName) {
File inputXml = new File(fileName);
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(inputXml);
Element employees = document.getRootElement();
for (Iterator i = employees.elementIterator(); i.hasNext();) {
Element employee = (Element) i.next();
for (Iterator j = employee.elementIterator(); j.hasNext();) {
Element node = (Element) j.next();
System.out.println(node.getName() + ":" + node.getText());
}
}
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
System.out.println("dom4j parserXml");
} @Override
public Map parserSmsXml(String sms) {
Map map = new HashMap();
// SAXReader saxReader = new SAXReader();
try {
Document document = DocumentHelper.parseText(sms);
Element returnsms = document.getRootElement();
for (Iterator i = returnsms.elementIterator(); i.hasNext();) {
// Element employee = (Element) i.next();
// for (Iterator j = employee.elementIterator(); j.hasNext();) {
Element node = (Element) i.next();
// System.out.println(node.getName() + ":" + node.getText());
map.put(node.getName(), node.getText());
// }
}
} catch (DocumentException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return map;
}
}
4.测试parserSmsXml方法
@Test
public void testParserSmsXml(){
String sms = "<?xml version='1.0' encoding='utf-8' ?><returnsms>"+
"<returnstatus>Success</returnstatus>"+
"<message>ok</message>"+
"<remainpoint>76904</remainpoint>"+
"<taskID>5002192</taskID>"+
"<successCounts>1</successCounts></returnsms>";
XmlDocument d = new Dom4j();
Map map = d.parserSmsXml(sms);
System.out.println(map);
}