這個範例程式碼是來自Java Tips,ㄚ琪覺得好用就拿來這邊獻醜翻譯了,如果有涉及翻譯侵權的話,尚請告知。
這個範例程式碼使用DOM剖析器來讀取XML檔案,DOM剖析器載入XML檔案到記憶體中並產生一個物件模型,這個物件模型可以遍歷以取得它的元素。
這個程式碼會剖析下面的MyXMLFile.xml檔案並印出它的元素到控制台。
XML file: MyXMLFile.xml
<?xml version="1.0"?> <company> <employee> <firstname>Tom</firstname> <lastname>Cruise</lastname> </employee> <employee> <firstname>Paul</firstname> <lastname>Enderson</lastname> </employee> <employee> <firstname>George</firstname> <lastname>Bush</lastname> </employee> </company>
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReader {
public static void main(String argv[]) {
try {
File file = new File(“c:MyXMLFile.xml”);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println(“Root element ” + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName(“employee”);
System.out.println(“Information of all employees”);
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(“firstname”);
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println(“First Name : ” + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName(“lastname”);
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println(“Last Name : ” + ((Node) lstNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
1 則留言