• Dom解析xml


    /**
    * 用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;
    }
    }

  • 相关阅读:
    三次握手与四次挥手原理
    动态主机配置协议(DHCP)
    网络知识-OSI7层模型说明和相关协议
    企业面试题合集
    优先队列(priority_queue)自定义排序方法
    优先队列(priority_queue)自定义排序方法
    C. Playlist(权值线段树查询前k大和)
    C. Playlist(权值线段树查询前k大和)
    C++判断四个点能否构成正方形/矩阵
    C++判断四个点能否构成正方形/矩阵
  • 原文地址:https://www.cnblogs.com/lingl/p/10342562.html
Copyright © 2020-2023  润新知