java实现xml格式化,不使用现有的xml库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/TK_lTlei/article/details/78939525

如图示:
这里写图片描述

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String s = in.nextLine();
            String temp = "";
            char temp_char = 0;
            Stack<String> stack = new Stack<String>();
            int j = 0;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '<') {
                    if (i > 0)
                        temp_char = s.charAt(i - 1);
                    System.out.print(temp);
                    temp = "";
                } else if (c == '>') {

                    if (!stack.isEmpty() && temp.equals(stack.peek())) {
                        // System.out.println(1);
                        stack.pop();
                        if (temp_char == '>') {
                            for (j = 0; j < stack.size(); j++) {
                                System.out.print(" ");
                            }
                        }
                        System.out.println("</" + temp + c);
                    } else {
                        for (j = 0; j < stack.size(); j++) {
                            System.out.print(" ");
                        }
                        if (s.charAt(i + 1) == '<') {
                            System.out.println("<" + temp + c);
                        } else
                            System.out.print("<" + temp + c);
                        stack.push(temp);
                    }
                    temp = "";
                    // System.out.println("");
                } else if (c == '/') {
                } else
                    temp += c;
            }

        }

    }
}

猜你喜欢

转载自blog.csdn.net/TK_lTlei/article/details/78939525
今日推荐