ホームページへ戻る
 

上へ戻る
 

// JAXP packages
import javax.xml.parsers.*;
import org.w3c.dom.*;

import java.io.*;

public class domlist {
static final String outputEncoding = "EUC_JP";
private PrintWriter out;
private int indent = 0;

/** Indentation will be in multiples of basicIndent */
private final String basicIndent = " ";

domlist(PrintWriter out) {
this.out = out;
}


/* Echo common attributes of a DOM2 Node and terminate output with an
EOL character. */
private void printlnCommon(Node n) {
out.print(" nodeName=\"" + n.getNodeName() + "\"");

String val = n.getNamespaceURI();

if (val != null) {
out.print(" uri=\"" + val + "\"");
}
val = n.getPrefix();
if (val != null) {
out.print(" pre=\"" + val + "\"");
}
val = n.getLocalName();
if (val != null) {
out.print(" local=\"" + val + "\"");
}
val = n.getNodeValue();
if (val != null) {
out.print(" nodeValue=");
if (val.trim().equals("")) {
// Whitespace
out.print("[WS]");
} else {
out.print("\"" + n.getNodeValue() + "\"");
}
}
out.println();
}
/* Indent to the current level in multiples of basicIndent */
private void outputIndentation() {
for (int i = 0; i < indent; i++) {
out.print(basicIndent);
}
}

/* Recursive routine to print out DOM tree nodes */
private void echo(Node n) {
// Indent to the current level before printing anything
outputIndentation();

int type = n.getNodeType();
switch (type) {
case Node.ATTRIBUTE_NODE:
out.print("ATTR:");
printlnCommon(n);
break;
case Node.CDATA_SECTION_NODE:
out.print("CDATA:");
printlnCommon(n);
break;
case Node.COMMENT_NODE:
out.print("COMM:");
printlnCommon(n);
break;
case Node.DOCUMENT_NODE:
out.print("DOC:");
printlnCommon(n);
break;
case Node.TEXT_NODE:
out.print("TEXT:");
printlnCommon(n);
break;
case Node.ELEMENT_NODE:
out.print("ELEM:");
printlnCommon(n);

// Print attributes if any. Note: element attributes are not
// children of ELEMENT_NODEs but are properties of their
// associated ELEMENT_NODE. For this reason, they are printed
// with 2x the indent level to indicate this.
NamedNodeMap atts = n.getAttributes();
indent += 2;
for (int i = 0; i < atts.getLength(); i++) {
Node att = atts.item(i);
echo(att);
}
indent -= 2;
break;
default:
out.print("UNSUPPORTED NODE: " + type);
printlnCommon(n);
break;
}
// Print children if any
indent++;
for (Node child = n.getFirstChild(); child != null;
child = child.getNextSibling()) {
echo(child);
}
indent--;
}

public static void main(String[] args) throws Exception {
String filename = null;

filename = args[0];
if (filename == null) {
System.out.println("ファイル名を入力してください!");
System.exit(1);
}
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(filename));
OutputStreamWriter outWriter =
new OutputStreamWriter(System.out, outputEncoding);
new domlist(new PrintWriter(outWriter, true)).echo(doc);
}
}