package com.kdgregory.example.xml.builder;

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;


public class StringBased
{
    public static void main(String[] argv)
    throws Exception
    {
        StringBuffer sb = new StringBuffer();
        sb.append("<albums>\n");
        appendEntry(sb,
            "Anderson, Laurie",
            new String[] {"Big Science", "Home of the Brave", "Strange Angels"});
        appendEntry(sb,
            "Fine Young Cannibals",
            new String[] {"The Raw & The Cooked"});
        sb.append("<albums>\n");
        System.out.println(sb);
        tryToParse(sb.toString());
    }


    public static Document tryToParse(String xml)
    throws Exception
    {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        return db.parse(new InputSource(new StringReader(xml)));
    }


    public static void appendEntry(StringBuffer buf, String artist, String[] albums)
    {
        buf.append("  <artist name=\"").append(artist).append("\">\n");
        for (String album : albums)
        {
            buf.append("    <album>").append(album).append("</album>\n");
        }
        buf.append("  </artist>\n");
    }
}
