
import java.io.File;
import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.CharacterData;
import org.xml.sax.SAXException;

public class DomParser
{
	static public String getCharData(Node p)
	{
		StringBuffer sb = new StringBuffer();
		CharacterData cdata;

		while (p != null)
		{
			switch (p.getNodeType())
			{
				case Node.TEXT_NODE:
				case Node.CDATA_SECTION_NODE:
					cdata = (CharacterData)p;
					sb.append(cdata.getData());
					break;
			}
			p = p.getNextSibling();
		}

		return sb.toString();
	}

	static void walk(Node node)
	{
		NodeList nl = node.getChildNodes();

		for (int i = 0; i < nl.getLength(); i++)
		{
			Node n = nl.item(i);

			if (n.getNodeType() != Node.ELEMENT_NODE)
				continue;

			System.out.println(n.getNodeName());

			walk(nl.item(i));
		}
	}

	public static void main(String[] args)
	{
		Document doc;

		if (args.length != 1)
		{
			System.err.println("Usage: java DomParser <xmlfile>");
			System.exit(-1);
		}

		try
		{
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = builderFactory.newDocumentBuilder();

			File file = new File(args[0]);
			doc = builder.parse(file);

			// Í staðinn fyrir að lesa inn streng til að þátta er hægt
			// að láta þáttarann fá straum (InputStream), t.d.
			// builder.parse(gengi.openStream());

			// Hægt að nota t.d. doc.getElementsByTagName hér.

			walk(doc);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
