// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XmlSniffer {
    private static Pattern either = Pattern.compile("(\\<[\\w-]+.*?\\>)|(\\</[\\w-]+\\>)");
    private static Pattern start = Pattern.compile("\\<[\\w-]+.*?\\>");
    private static Pattern end = Pattern.compile("\\</[\\w-]+\\>");
    private static Pattern both = Pattern.compile("\\<[\\w-]+.*?/\\>");
    public static boolean check(String xmlstr) {
        Matcher e = either.matcher(xmlstr);
        int depth = 0;
        boolean first = true;
        while(e.find()) {
            String piece = e.group();
            if(start.matcher(piece).matches()) {
                if(depth == 0) {
                    if(first) {
                        first = false;
                    } else {
                        return false;
                    }
                }
                if(!both.matcher(piece).matches()) {
                    depth++;
                }
            } else if(end.matcher(piece).matches()) {
                depth--;
            }
        }
        return true;
    }
    private static void test(String xmlstr) {
        System.out.println(xmlstr);
        System.out.println(check(xmlstr));
    }
    public static void main(String[] args) {
        test("<a/>");
        test("<a>xxxx</a>");
        test("<a>\r\n    <b>xxxx</b>\r\n</a>");
        test("<a>\r\n    <b/>\r\n</a>");
        test("<a>xxxx</a>\r\n<c>yyyy</c>");
        test("<a>\r\n    <b>xxxx</b>\r\n</a>\r\n<c>yyyy</c>");
        test("<a>\r\n    <b/>\r\n</a>\r\n<c>yyyy</c>");
        test("<a>xxxx</a>\r\n<c/>");
        test("<a>\r\n    <b>xxxx</b>\r\n</a>\r\n<c/>");
        test("<a>\r\n    <b/>\r\n</a>\r\n<c/>");
        test("<a/>\r\n<c/>");
    }
}
