10 November 2016

Read XML Using DOM in Java

Đọc XML với DOM
products.xml
Java XML 2016
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<products>
    <product id="p1">
        <name>Name 1</name>
        <price>20</price>
    </product>
    <product id="p2">
        <name>Name 2</name>
        <price>26</price>
    </product>
    
</products>
ProductDOM.java
Java XML 2016
package dom;

import java.util.logging.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class ProductDOM {

    public void Display() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document d = (Document) db.parse("src\\data\\products.xml");
            
            NodeList nl = d.getElementsByTagName("product");
            
            System.out.println("Number of product:" +nl.getLength());
            System.out.println("List product infomation");
            
            for(int i=0; i< nl.getLength(); i++){
                Element el = (Element) nl.item(i);
                NamedNodeMap nnm = el.getAttributes();
                if(nnm.getLength() >0){
                    System.out.println("Id: "+nnm.item(0).getTextContent());
                    System.out.println("Name: "+el.getElementsByTagName("name").item(0).getTextContent());
                    System.out.println("Price: "+el.getElementsByTagName("price").item(0).getTextContent());
                }
            }
                
        } catch (Exception ex) {
            Logger.getLogger(ProductDOM.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
Main.java
Java XML 2016
package dom;

public class Main {
    public static void main(String[] args) {
        ProductDOM px = new ProductDOM();
        px.Display();
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang