import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

/** xerces-2_9_0のテスト
 *  テスト用のXMLを開き、内容を表示する。
 *  
 */
class Sample
{

	public static void main(String args[])
	{
		DocumentBuilder builder;
		Node root;
		
		System.out.println("\nXMLパーサーファクトリ");
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(true);
		try{
			builder = factory.newDocumentBuilder();
		}
		catch(ParserConfigurationException e)
		{
			return;
		}
		
		System.out.println("\nファイルを読み込む");
		String uri = "xmlsample.xml";
		try{
			root = builder.parse(uri);
		}
		catch(Exception e)
		{
			return;
		}
		
		System.out.println("\nルートノードにいる事を確認する");
		if (root.getNodeType() == Node.DOCUMENT_NODE) {
			System.out.println("Root is Document!");
		}
		
		Node child = root.getFirstChild();
		System.out.println("\n子ノードを取り出す");
		NodeList gchildren = child.getChildNodes();
		for (int i = 0; i < gchildren.getLength(); i++) {
			Node gchild = gchildren.item(i);
			if("#text".equals(gchild.getNodeName()))
			{
				continue;
			}
			System.out.println("Name: " + gchild.getNodeName()
				+ " Value: " + gchild.getFirstChild().getNodeValue());
		}
		
		System.out.println("\nすべてのノードを取り出す");
		NodeTest(root, 0);
	}
	
	/** 構文解析サンプル
	 *  今はただ表示するだけ
	 *  @param node  = 親ノード
	 *  @param depth = 親ノードのXMLインデント深さ
	 */
	public static void NodeTest(Node node, int depth)
	{
		if("#text".equals(node.getNodeName()))
		{
			System.out.println(getIndentText(depth) + node.getNodeValue().trim());
		}
		else
		{
			System.out.println(getIndentText(depth) + "<" + node.getNodeName() + ">");
			NodeList gchildren = node.getChildNodes();
			for (int i = 0; i < gchildren.getLength(); i++) {
				Node gchild = gchildren.item(i);
				NodeTest(gchild, depth + 1);
			}
			System.out.println(getIndentText(depth) + "</" + node.getNodeName() + ">");
		}
	}
	
	/** 表示用にインデントをつける
	 *  @param depth = XMLインデント深さ
	 */
	public static String getIndentText(int depth)
	{
		String s = "";
		for(int i = 0; i < depth; i++)
		{
			s += "　　";
		}
		return s;
	}

}


		/*
		System.out.println("\nノードの属性を取り出す");
		NamedNodeMap attributes = child.getAttributes();
		NodeList gattributes = attributes.getChildNodes(); 
		for (int i = 0; i < gattributes.getLength(); i++) {
			Node gchild = gattributes.item(i);
			if("#text".equals(gchild.getNodeName()))
			{
				continue;
			}
			System.out.println("Name: " + gchild.getNodeName()
				+ " Value: " + gchild.getFirstChild().getNodeValue());
		}
		Node id = attributes.getNamedItem("id");
		System.out.println(id.getNodeName());
		System.out.println(id.getNodeValue());
		*/

