[Solved] How to Parse XML without using DOM or SAX Parser in Java?


First of all, parsing XML by hand is nothing but inviting bugs and gotchas!.

Since you must do it without standard parsers and want a tailor-made parsing for a specific XML, here is something you could do to get rid of unreadable code(at least). Now, talking about O(1) space complexity. Assumption is that the XML is small and you are OK to read it fully in one shot; and then break the input, there seems to be no way to have constant space.

    String[] persons = data.split("person[\\d]");
    HashMap<Integer, StringBuilder> outputMap = new HashMap<>();
    outputMap.put(0,new StringBuilder("Name | Age | Designation | Date | HomeTown"));
    for(int i=0;i<persons.length;i++) {
        if(persons[i].contains("<Name>")){
            outputMap.put(i + 1, new StringBuilder()
                    .append(persons[i].split("</*Name>")[1]).append("|")
                    .append(persons[i].split("</*Age>")[1]).append("|")
                    .append(persons[i].split("</*Designation>")[1]).append("|")
                    .append(persons[i].split("</*Date>")[1]).append("|")
                    .append(persons[i].split("</*Hometown>")[1]));
        }
    }
    Collection<StringBuilder> outputData = outputMap.values();
    for(StringBuilder output: outputData){
        System.out.println(output);
    }

1

solved How to Parse XML without using DOM or SAX Parser in Java?