Example1: ["Valid" XML Document]["Valid" XML Document .dtd]
["Valid" XML Document .xml]
//xmlDoc.load(".xml")是载入文件 | xmlDoc.loadXML(text)载入String
[.xml]
[Use DOM]
1/** *//**Factory Pattern 2 * DocumentBuilderFactory.newInstance().DocumentBuilder(); 3 * DocumentBuilder.parse(File) --> Document; 4 * (Element extends Node) 5 * Document.getDocumentElement().getNodeName() --> Root!; 6 */ 7 8import javax.xml.parsers.DocumentBuilderFactory; 9import javax.xml.parsers.DocumentBuilder;10import java.io.File;11import javax.xml.parsers.FactoryConfigurationError;12import org.w3c.dom.Document;13import org.w3c.dom.Node;14import org.w3c.dom.Element;15import org.w3c.dom.NodeList;1617public class FirstXML {18 /** *//**19 * @param args20 */21 public static void main(String[] args) {22 // TODO Auto-generated method stub23 try {24 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();25 DocumentBuilder db = dbf.newDocumentBuilder();26 Document doc = db.parse(new File("D:\\eclipse\\WS\\testXML\\user.xml"));27 /**//*System.out.println(doc.getTextContent());28 System.out.println(doc.getDoctype());29 System.out.println(doc.getDocumentURI());30 System.out.println(doc.getNodeType());31 System.out.println(doc.getXmlEncoding());32 System.out.println(doc.getXmlVersion());*/33 34 //Roots35 Node no = doc.getDocumentElement();36 System.out.println(no.getNodeName());37 NodeList nl = doc.getElementsByTagName("user");38 //System.out.println(no.getTextContent()); //Context39 for(int i=0; i<nl.getLength(); i++) {40 System.out.println("userName: " + 41 doc.getElementsByTagName("name").item(i).getTextContent());42 System.out.println("sex: " + 43 doc.getElementsByTagName("sex").item(i).getTextContent());44 }45 }catch(Exception e) { e.printStackTrace();}46 }47}48