/**
* 用DOM方式读取xml文件
*
* @author lune
*/
public class ReadxmlByDom {
private List<Result> results = null;
private Result result = null;
public List<Result> getResults(String message) {
int success = message.indexOf("<success>");
int failure = message.indexOf("<failure>");
int exception = message.indexOf("<exception>");
// 创建一个新的字符串
StringReader read = new StringReader(message);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder saxbBuilder = new SAXBuilder();
try {
// 通过输入源构造一个Document
Document document = saxbBuilder.build(source);
// 获取根节点result
Element rootElement = document.getRootElement();
// 获取根节点的子节点,返回子节点的数组
List<Element> resultList = rootElement.getChildren();
if(success!=-1) {
results = new ArrayList<Result>();
result = new Result();
Element resultElement = resultList.get(0);
// 获取resultElement的子节点
List<Element> children = resultElement.getChildren();
for (Element child : children) {
result.setMsgId(child.getAttributeValue("msgId"));
}
results.add(result);
}else if (failure != -1) {
results = new ArrayList<Result>();
result = new Result();
Element resultElement = resultList.get(1);
// 获取resultElement的子节点
List<Element> children = resultElement.getChildren();
for (Element child : children) {
result.setDesc(child.getAttributeValue("desc"));
}
results.add(result);
} else if (exception != -1) {
results = new ArrayList<Result>();
result = new Result();
Element resultElement = resultList.get(0);
// 获取resultElement的子节点
List<Element> children = resultElement.getChildren();
for (Element child : children) {
System.out.println(child.getName());
if(child.getName().equals("desc")) {
System.out.println(child.getValue());
result.setDesc(child.getValue());
}
}
results.add(result);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
}