Đọc XML với DOM
sinhvien.xml
Java XML 2016
<?xml version="1.0" encoding="UTF-8"?>
<sinhvien>
<masv>sv01</masv>
<hoten>sinh vien 01</hoten>
</sinhvien>
DOM.java
Java XML 2016
package demosax; 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; public class DOM { public void hienthi() { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse("src\\database\\sinhvien.xml"); Element root = d.getDocumentElement(); System.out.println("Ten node goc: "+root.getNodeName()); //Lay gia tri masv Node masv = root.getElementsByTagName("masv").item(0); System.out.println(masv.getNodeName() +" : "+masv.getTextContent()); //Lay gia tri hoten Node hoten = root.getElementsByTagName("hoten").item(0); System.out.println(hoten.getNodeName() +" : "+hoten.getTextContent()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
DemoSAX.java
Java XML 2016
package demosax;
public class DemoSAX {
public static void main(String[] args) {
DOM dssv = new DOM();
dssv.hienthi();
}
}
0 nhận xét:
Post a Comment