Java XML教程(一)__教程 |
|
日期:2007-5-20 1:28:04 人气:234 [大 中 小] |
|
|
|
/** * domOne.java * Illustrates how to go through a DOM tree. */
public class domOne { public void parseAndPrint(String uri) { Document doc = null;
try { DOMParser parser = new DOMParser(); parser.parse(uri); doc = parser.getDocument(); } catch (Exception e) { System.err.println("Sorry, an error occurred: " + e); }
// We`ve parsed the document now, so let`s print it. if (doc != null) printDOMTree(doc); }
/** Prints the specified node, then prints all of its children. */ public void printDOMTree(Node node) { int type = node.getNodeType(); switch (type) { // print the document element case Node.DOCUMENT_NODE: { System.out.println(""); printDOMTree(((Document)node).getDocumentElement()); break; }
// print element with attributes case Node.ELEMENT_NODE: { System.out.print("<"); System.out.print(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); System.out.print(" " + attr.getNodeName() + "="" + attr.getNodeValue() + """); } System.out.println(">");
NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) printDOMTree(children.item(i)); }
break; }
// handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { System.out.print("&"); System.out.print(node.getNodeName()); System.out.print(";"); break; }
// print cdata sections case Node.CDATA_SECTION_NODE: { System.out.print("System.out.print(node.getNodeValue()); System.out.print("]]>"); break; }
// print text case Node.TEXT_NODE: { System.out.print(node.getNodeValue()); break; }
// print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { System.out.print(""); System.out.print(node.getNodeName()); String data = node.getNodeValue(); { System.out.print(" "); System.out.print(data); } System.out.print("?>"); break; } }
if (type == Node.ELEMENT_NODE) { System.out.println(); System.out.print(""); System.out.print(node.getNodeName()); System.out.print(`>`); } }
/** Main program entry point. */ public static void main(String argv[]) { if (argv.length == 0) { System.out.println("Usage: java domOne uri"); System.out.println(" where uri is the URI of the XML document you want to print."); System.out.println(" Sample: java domOne sonnet.xml"); System.exit(1); }
domOne d1 = new domOne(); d1.parseAndPrint(argv[0]); } }
domCounter.java
这段代码解析一个 XML 文档,然后遍历 DOM 树来采集有关该文档的数据。当数据采集后将其输出到标准输出。 |
|
出处:本站原创 作者:佚名 |
|
|