java SpitElements <nom du fichier>
java SpitElements ../formcont.xml
DOMParser parser = new DOMParser();
parser.parse(filename);
// The document is the root of the DOM tree.
Document doc = parser.getDocument();
// Get the Document Element (Top Node)
Element root = (Element)doc.getDocumentElement();
// Do something with this Node
walkDOMBranch(root);
public static void walkDOMBranch(Node node) {
// print the name and value (characters) of the Node
System.out.println(node.getNodeName()+":"+node.getNodeValue());
// if the node has children do the same thing for each child
if (node.hasChildNodes()) {
NodeList nodeList = node.getChildNodes();
int size = nodeList.getLength();
for (int i = 0; i < size; i++) {
walkDOMBranch(nodeList.item(i));
}
}
} }
La classe Element:
Elements represent most of the "markup" and structure of the document. They contain both the data for the element itself (element name and attributes), and any contained nodes, including document text (as children). Elements may have Attributes associated with them; the API for this is defined in Node, but the function is implemented here.
try { ......
parser.parse(filename);
......
} catch (Exception e) {
System.out.println("Something is wrong ...");
e.printStackTrace(System.err) }
catch (SAXParseException e) {
System.out.println("The File is not well formed.");
System.out.println(e.getMessage()
+ " at line " + e.getLineNumber()
+ ", column " + e.getColumnNumber());
}
catch (SAXException e) {
System.out.println("SAX exception found");
System.out.println(e.getMessage());
e.printStackTrace(System.out);
}
Document doc = parser.getDocument();
printElements(doc.getElementsByTagName("title"));
......
public void printElements(NodeList listOfNodes) {
for (int i=0; i<listOfNodes.getLength();i++) {
Element node = (Element) listOfNodes.item(i);
out.println("Node Name = " + node.getNodeName());
// out.println("Node Value = " + node.getNodeValue());
out.println("String Value= " + node.getFirstChild().getNodeValue());
}
}
Rappel: La classe Element: Contains both the data for the element itself (element name and attributes), and any contained nodes, including document text (as children).