JAVA学习笔记Day09——JAVA用正则表达式简单解析

利用简单表达式、堆栈方法处理简单XML的解析

package net.xiaohong.xml;


import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Project :Learon09
 * Created :
 * Date : 2016/8/2
 */
public class Test01 {
    public static void main(String[] args) {
        String str = "\n" +
                "    \n" +
                "        JAVA基础\n" +
                "        30.00\n" +
                "    \n" +
                "    \n" +
                "        JAVA入门\n" +
                "        30.00\n" +
                "    \n" +
                "    \n" +
                "        JAVA精通\n" +
                "        30.00\n" +
                "    \n" +
                "    \n" +
                "        颈椎康复指南\n" +
                "        90.00\n" +
                "    \n" +
                "\n" + "" +
                "";


        Pattern pattern = Pattern.compile("<(/?)([^<>/]+)(/?)>");
        Matcher matcher = pattern.matcher(str);

        Stack stack = new Stack<>();
        Stack last = new Stack<>();
        List list = null;

        while (matcher.find()) {
            if (matcher.group(1).isEmpty()) {
                last.push(matcher.end());
                switch (matcher.group(2)) {
                    case "Books":
                        list = new ArrayList<>();
                        break;
                    case "Book":
                        stack.push(new Book());
                        break;
                }
                if (!matcher.group(3).isEmpty()) {
                    switch (matcher.group(2)) {
                        case "Book":
                            last.add(last.pop());
                            break;
                    }
                }
            }else {
                Integer pop = last.pop();
//                System.out.println(pop);
                switch (matcher.group(2)) {
                    case "Book":
                        list.add(stack.pop());
                        break;
                    case "Name":
                        stack.peek().setName(str.substring(pop,matcher.start()));
                        break;
                    case "Price":
                        stack.peek().setPrice(Float.parseFloat(str.substring(pop,matcher.start())));
                        break;
                }
            }
        }
        for (Book book : list) {
            System.out.println(book);
        }
    }
}

JAVA学习笔记Day09——JAVA用正则表达式简单解析_第1张图片

你可能感兴趣的:(程序开发,JAVA学习)