// 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.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.apache.xpath.XPathAPI;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class TwoLevelXml {
    private static void parseSecondLevel(String xml) throws ParserConfigurationException, SAXException, IOException, DOMException, TransformerException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(xml)));
        String a = XPathAPI.selectSingleNode(doc.getDocumentElement(), "//rec/a/text()").getNodeValue();
        String b = XPathAPI.selectSingleNode(doc.getDocumentElement(), "//rec/b/text()").getNodeValue();
        System.out.println(a);
        System.out.println(b);
    }
    private static void parseFirstLevel(String xml) throws ParserConfigurationException, SAXException, IOException, DOMException, TransformerException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(xml)));
        String hdr = XPathAPI.selectSingleNode(doc.getDocumentElement(), "//main/header/text()").getNodeValue();
        String body = XPathAPI.selectSingleNode(doc.getDocumentElement(), "//main/body/text()").getNodeValue();
        System.out.println(hdr);
        System.out.println(body);
        parseSecondLevel(body);
    }
    public static void main(String[] args) throws Exception {
        parseFirstLevel("<main><header>Test</header><body><![CDATA[<rec><a>1</a><b>2</b></rec>]]></body></main>");
    }
}
