dom4j解析xml字符串实例

 

项目中实例:

拼装XML:

 

Element root = DocumentHelper.createElement("root");
                Element set = null;
                String aimSql = "SELECT " + queryField + " FROM t_jgdm WHERE 1=1 " + queryCondition;
                pstmt = conn.prepareStatement(aimSql);
                System.out.println("【代码共享SQL:】" + aimSql);
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    set = root.addElement("set");
                    String[] queryFieldArr = queryField.split(",");
                    for (int i = 0; i < queryFieldArr.length; i++) {
                        set.addAttribute(queryFieldArr[i], rs.getString(queryFieldArr[i].toUpperCase()));
                    }
                }
                res = root.asXML();
 

解析XML:

Document document = DocumentHelper.parseText(res);
            Element root = document.getRootElement();
            Element set = (Element) root.selectSingleNode("/root");
            Iterator<Element> iterator = set.elementIterator("set");
            Element element = null;
            while (iterator.hasNext()) {
                element = iterator.next();
                Iterator iter = element.attributeIterator();
                while (iter.hasNext()) {
                    Attribute attribute = (Attribute) iter.next();
                    System.out.println(attribute.getName() + ":" + element.attributeValue(attribute.getName()));
                }
            }

 

参考:http://www.cnblogs.com/macula/archive/2011/07/27/2118003.html

 

你可能感兴趣的:(xml,dom4j)