java解析xml字符串——DOM(Document Object Model)

package com.test;

/**
 * Created by admin on 2018/7/16.
 */

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


public class test{

    public static void main(String[] args) {

  

       String xml = "" +
                "" +
                "" +
                "1001" +
                "wangwei" +
                "80" +
                "1001号" +
                "" +
                "" +
                "1002" +
                "wangwei" +
                "80" +
                "1002号" +
                "" +
                "" +
                "1002_1" +
                "wangwei_1" +
                "80_1" +
                "1002号_1" +
                "" +
                "";

        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称
            Iterator iter = rootElt.elementIterator("row"); // 获取根节点下的子节点row
            Iterator iter1 = rootElt.elementIterator("row1");
            // 遍历row节点
            while (iter.hasNext()) {
                Element recordEle = (Element) iter.next();
                String users_id = recordEle.elementTextTrim("users_id"); // 拿到row节点下的子节点row值
                String users_name = recordEle.elementTextTrim("users_name");
                String users_group = recordEle.elementTextTrim("users_group");
                String users_address = recordEle.elementTextTrim("users_address");
                System.out.println("users_id:" + users_id);
                System.out.println("users_name:" + users_name);
                System.out.println("users_group:" + users_group);
                System.out.println("users_address:" + users_address);
            }

            // 遍历row1节点
            while (iter1.hasNext()) {
                Element recordEle = (Element) iter1.next();
                String users_id = recordEle.elementTextTrim("users_id"); // 拿到row节点下的子节点row值
                String users_name = recordEle.elementTextTrim("users_name");
                String users_group = recordEle.elementTextTrim("users_group");
                String users_address = recordEle.elementTextTrim("users_address");
                System.out.println("users_id:" + users_id);
                System.out.println("users_name:" + users_name);
                System.out.println("users_group:" + users_group);
                System.out.println("users_address:" + users_address);
            }



        } catch (Exception e) {

        }


    }
}

 

你可能感兴趣的:(java基础)