-- 作者:sxhong
-- 发布时间:11/10/2004 11:23:00 PM
--
你看一下下面的两个程序吧,可以解析的,不过是比较简单的 //////DOMDisplay用于XML文档的输出//////// import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; public class DOMDisplay { public static void display (Node start) { if (start.getNodeType() == start.ELEMENT_NODE) { System.out.print("<"+start.getNodeName()); NamedNodeMap startAttr = start.getAttributes(); for (int i = 0; i < startAttr.getLength(); i++) { Node attr = startAttr.item(i); System.out.print(" "+attr.getNodeName()+ "=\""+attr.getNodeValue()+"\""); } System.out.print(">"); } else if (start.getNodeType() == start.TEXT_NODE) { System.out.print(start.getNodeValue()); } for (Node child = start.getFirstChild();child != null;child = child.getNextSibling()) { display(child); } if (start.getNodeType() == start.ELEMENT_NODE) { System.out.print("</"+start.getNodeName()+">"); } } } //////////////DocBuildDemo生成Document对象并通过上面的DOMDisplay.display(doc)输出,其中quotations.xml为一个有效的XML文档/// import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; public class DocBuildDemo { public static void main (String args[]){ DocumentBuilderFactory dbf = null; DocumentBuilder db = null; Document doc = null; try { dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.out.print("Could not replace parser: "); System.out.println(pce.getMessage()); } try { doc = db.parse("quotations.xml"); } catch (java.io.IOException ie){ System.out.println("Could not read file."); } catch (SAXException e) { System.out.print("Could not create Document: "); System.out.println(e.getMessage()); } System.out.println("用DocumentBuilderFactory解析"); DOMDisplay.display(doc); } }
|