Ví dụ Java đơn giản bắt đầu với DOM
Xem thêm các chuyên mục:
Ví dụ đơn giản

xml-file01.xml
<?xml version="1.0" ?> <rootOfXml> This is text 01 <myElement1>This is text in myElement1</myElement1> <!--This is Comment --> This is text 02 <?myTarget01 This is My ProcessingInstruction ?> </rootOfXml>
BeginDOMExample.java
package org.o7planning.tutorial.xmldom.example01; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; public class BeginDOMExample { private void parseNow() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Sét đặt việc kiểm tra tính hợp lệ của tài liệu sẽ phân tích sau này factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream inputStream = BeginDOMExample.class .getResourceAsStream("/org/o7planning/tutorial/xmldom/xml/xml-file01.xml"); InputSource inputSource = new InputSource(inputStream); // Lấy ra đối tượng Document bằng cách phân tích InputSource Document doc = builder.parse(inputSource); // Lấy ra phần tử gốc của tài liệu. Element root = (Element) doc.getDocumentElement(); // In ra man hinh ten cua phan tu goc cua tai lieu XML xmlFile.xml la gi System.out.println("Root name:" + root.getNodeName()); } /** Main Method */ public static void main(String[] args) { BeginDOMExample f = new BeginDOMExample(); try { f.parseNow(); } catch (Exception e) { e.printStackTrace(); } } }
Kết quả chạy ví dụ:
Root name:rootOfXml