10 November 2016

Read XML Using XPath in Java

Đọc XML với XPath
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>
products.xml
Java XML 2016
package dom;

/**
 *
 * @author Lonely
 */
public class Main {
    public static void main(String[] args) {
        ProductXPath px = new ProductXPath();
        px.Display();
    }
}
products.xml
Java XML 2016
package dom;

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

/**
 *
 * @author Lonely
 */
public class ProductXPath {

    public void Display() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document d = (Document) db.parse("src\\data\\products.xml");
            
            XPath xp = XPathFactory.newInstance().newXPath();
            NodeList nl = (NodeList)xp.compile("//product").evaluate(d, XPathConstants.NODESET);
            
            System.out.println("Number of product: "+nl.getLength());
            System.out.println("List product infomation");
            
            for(int i=0; i< nl.getLength(); i++){
                System.out.println("=====================");
                System.out.println("Id: "+xp.compile("./@id").evaluate(nl.item(i)));
                System.out.println("Name: "+xp.compile("./name").evaluate(nl.item(i)));
                System.out.println("Price: "+xp.compile("./price").evaluate(nl.item(i)));
            }
                
        } catch (Exception ex) {
            Logger.getLogger(ProductXPath.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang