SAXReader解析XML
总结:
Document document=new SAXReader.reader(“xml文路径/文件名xxx.xml”);//得到Document对象
Element root = document.getRootElement()//获得根节点
Iterator iterator=root.elementIterator(); //从根节点遍历子节点
Iterator iterator=Element.elementIterator(); //再从子节点在遍历其子节点
对节点访问其属性用:Attribute leaderAttr =Element. attribute(“xxx”);
对节点访问其某个属性leaderAttr的名称:leaderAttr.getName();对节点访问其某个属性leaderAttr的值:leaderAttr.getValue()
对节点访问其名称:Element.getName();
对节点访问其文本:Element. getText();
//SAXReader解析XML
public List<SMS> parseXML(String content) throws Exception{
/**
* <?xml version="1.0" encoding="UTF-8"?>
<mo>
<mescode>0</mescode>
<msgs>
<msg>
<mob>111111111</mob>
<content>生生世世</content>
</msg>
</msgs>
</mo>
*/
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(content));
if(document == null) {
log.error("解析XML失败:"+content);
return null;
}
Element e = (Element) document.selectSingleNode("/mo/mescode");
if(e == null) {
log.error("解析mescode节点失败:"+content);
return null;
}
int result = Integer.parseInt(e.getText());
switch(result){
/**
* 0 成功
1 失败
2 错误
*/
case 0:
List<SMS> messages = new ArrayList<SMS>();
List<Node> nodes = document.selectNodes("/mo/msgs/msg");
if(nodes == null){
log.error("解析msg节点失败:"+content);
return null;
}
for(Node node : nodes){
SMS message = new SMS();
e = (Element) node.selectSingleNode("mob");
message.setMobliePhone(e.getText());
e = (Element)node.selectSingleNode("content");
message.setContnet(URLDecoder.decode(e.getText(), encoding));
messages.add(message);
}
return messages;
case 1:
log.error("失败");
break;
case 2:
log.error("错误");
break;
}
return null;
}
//构造XML
StringBuilder builder = new StringBuilder();
builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
builder.append("<mt>");
builder.append(String.format("<userid>%s</userid>", USERID));
builder.append(String.format("<pwd>%s</pwd>", PWD));
builder.append("<msgs>");
if(messages != null){
for(SMS message : messages){
builder.append("<msg>");
builder.append(String.format("<mob>%s</mob>", s%));
builder.append(String.format("<content>%s</content>", URLEncoder.encode(s%,"UTF-8")));
builder.append("</msg>");
}
}
builder.append("</msgs>");
builder.append("</mt>");