1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
import java.io.*;
import nu.xom.*;
public class NodeLister {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java nu.xom.samples.NodeLister URL");
return;
}
Builder builder = new Builder();
try {
Document doc = builder.build(args[0]);
Element root = doc.getRootElement();
listChildren(root, 0);
}
// indicates a well-formedness error
catch (ParsingException ex) {
System.out.println(args[0] + " is not well-formed.");
System.out.println(ex.getMessage());
}
catch (IOException ex) {
System.out.println(ex);
}
}
public static void listChildren(Node current, int depth) {
printSpaces(depth);
String data = "";
if (current instanceof Element) {
Element temp = (Element) current;
data = ": " + temp.getQualifiedName();
}
else if (current instanceof ProcessingInstruction) {
ProcessingInstruction temp = (ProcessingInstruction) current;
data = ": " + temp.getTarget();
}
else if (current instanceof DocType) {
DocType temp = (DocType) current;
data = ": " + temp.getRootElementName();
}
else if (current instanceof Text || current instanceof Comment) {
String value = current.getValue();
value = value.replace('\n', ' ').trim();
if (value.length() <= 20) data = ": " + value;
else data = ": " + current.getValue().substring(0, 17) + "...";
}
// Attributes are never returned by getChild()
System.out.println(current.getClass().getName() + data);
for (int i = 0; i < current.getChildCount(); i++) {
listChildren(current.getChild(i), depth+1);
}
}
private static void printSpaces(int n) {
for (int i = 0; i < n; i++) {
System.out.print(' ');
}
}
}
|