How to read XML using XPath in Java

后端 未结 8 1370
无人及你
无人及你 2020-11-21 05:38

I want to read XML data using XPath in Java, so for the information I have gathered I am not able to parse XML according to my requirement.

here is what I want to do

8条回答
  •  伪装坚强ぢ
    2020-11-21 05:58

    Getting started example:

    xml file:

    
        
            Snow Crash
            Neal Stephenson
            Spectra
            0553380958
            14.95
        
    
        
            Burning Tower
            Larry Niven
            Jerry Pournelle
            Pocket
            0743416910
            5.99
        
    
        
            Zodiac
            Neal Stephenson
            Spectra
            0553573862
            7.50
        
    
        
    
    
    

    Java code:

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Test;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    
    
    try {
    
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new File("c:\\tmp\\my.xml"));
    
        // normalize text representation
        doc.getDocumentElement().normalize();
        System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
    
        NodeList listOfBooks = doc.getElementsByTagName("book");
        int totalBooks = listOfBooks.getLength();
        System.out.println("Total no of books : " + totalBooks);
    
        for(int i=0; i

提交回复
热议问题