欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-24 07:53:17
...

如图示:
java实现xml格式化,不使用现有的xml库

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;
            }

        }

    }
}
相关标签: 格式化xml