Results 1 to 8 of 8
  1. #1
    ziggy is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default Parsing XML file using Xpath in jdk1.4

    The following code is used to extract a specific element's value using xpath in jdk1.5

    Java Code:
    import java.io.IOException;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    
    public class XPathExample {
    
      public static void main(String[] args) 
       throws ParserConfigurationException, SAXException, 
              IOException, XPathExpressionException {
    
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse("c:\\temp\\books.xml");
    
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr 
         = xpath.compile("//book[author='Neal Stephenson']/title/text()");
    
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue()); 
        }
    
      }
    
    }
    This uses xpath to extract all books title where the author is Neal Stephenson from the following xml

    Java Code:
    <inventory>
    <book year="2000">
        <title>Snow Crash</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553380958</isbn>
        <price>14.95</price>
    </book>
    
    <book year="2005">
        <title>Burning Tower</title>
        <author>Larry Niven</author>
        <author>Jerry Pournelle</author>
        <publisher>Pocket</publisher>
        <isbn>0743416910</isbn>
        <price>5.99</price>
    </book>
    
    <book year="1995">
        <title>Zodiac</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553573862</isbn>
        <price>7.50</price>
    </book>
    </inventory>
    Now this works fine on JDK5 but i am using jdk 1.4 Can this be converted to the java 1.4 equivalent?

    All i am trying to do is extract a value from an xml element. For example, in the above xml, i just want something that is the equivalent of getElementByTag("title").

    According to a response i got from another site [for some reason the forum is not allowing me to post the link], JAXP can be downloaded separately. This has confused me a bit as i read somewhere else that JAXP is included in jdk1.4

    Could someone please clarify this please and let me know what exactly i need to do to be able to use xpath in jdk1.4

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default

    Quote Originally Posted by ziggy View Post
    Could someone please clarify this please and let me know what exactly i need to do to be able to use xpath in jdk1.4
    I am not sure what exactly your question is now, but the javax.xml.xpath package is available since 1.5 see : javax.xml.xpath (Java 2 Platform SE 5.0)

    To use XPath in 1.4 you could use JDOM

    Java Code:
    import java.util.List;
    import org.jdom.Document;
    import org.jdom.Text;
    import org.jdom.input.SAXBuilder;
    import org.jdom.xpath.XPath;
    
    //.....
    	public static void main(String[] args) throws Exception {
    		Document doc = new SAXBuilder().build("c:\\temp\\books.xml");
    		List nameList = XPath.selectNodes(doc, "//book[author='Neal Stephenson']/title/text()");
    		for (int i = 0; i < nameList.size(); i++) {
    			System.out.println(((Text)nameList.get(i)).getValue());
    		}
    	}

  3. #3
    ziggy is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    The reason it is confusing is that there is conflicting information as to whether xpath is possible in jdk 1.4. For example, have a look at this page JAXP: Updating and Using &mdash; Java.net

    At the very bottom of the page there is a section that mentions that JAXP is included in 1.4 but somehow not accessible via the normal way. (At least thats how i interpreted it)

  4. #4
    ziggy is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    What is the difference between JDOM and JAXP?

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  6. #6
    ziggy is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    Ok i have tried this with JDOM because i think messing around with libraries in teh endorsed directory is not safe. I tried to parse the same xml file shown above with the following code using JDOM

    Java Code:
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.jdom.input.SAXBuilder;
    import org.jdom.xpath.XPath;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.xml.sax.SAXException;
    
    public class XPathExample {
    
      public static void main(String[] args) 
       throws ParserConfigurationException, SAXException, 
              IOException, Exception {
    	  
    	// import org.jdom.Document;
    	// import org.jdom.Element;
    	// import org.jdom.JDOMException;
    	// import org.jdom.input.SAXBuilder;
    	// import org.jdom.xpath.XPath;
    	 String fn = "c:\\temp\\books.xml";
    	 FileInputStream in = new FileInputStream(fn);
    	 SAXBuilder builder = new SAXBuilder();
    	 Document doc = builder.build(in);
    	 in.close();
    	 
    	 XPath xpath = XPath.newInstance("//book[author='Neal Stephenson']/title/text()");
    	 List list = xpath.selectNodes(doc);
    	 for (Iterator iter = list.iterator(); iter.hasNext();) {
    	  Element elem = (Element) iter.next();
    	   
    	  String childText = elem.getChild("child").getTextTrim();
    	  String text = elem.getTextTrim();
    	  
    	  System.out.println("Value : " + text);
    	 }	 
      }
    }
    But it fails with a class cast exception at the line with

    Java Code:
    Element elem = (Element) iter.next();

  7. #7
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default

    In your XPath you are selecting text() at the end, so iter.next() will return a Text-object, not an element, looking at my code!
    Last edited by eRaaaa; 02-27-2011 at 12:56 PM. Reason: at the end :D

  8. #8
    ziggy is offline Member
    Join Date
    Nov 2008
    Posts
    11
    Rep Power
    0

    Default

    Quote Originally Posted by eRaaaa View Post
    I am not sure what exactly your question is now, but the javax.xml.xpath package is available since 1.5 see : javax.xml.xpath (Java 2 Platform SE 5.0)

    To use XPath in 1.4 you could use JDOM

    Java Code:
    import java.util.List;
    import org.jdom.Document;
    import org.jdom.Text;
    import org.jdom.input.SAXBuilder;
    import org.jdom.xpath.XPath;
    
    //.....
    	public static void main(String[] args) throws Exception {
    		Document doc = new SAXBuilder().build("c:\\temp\\books.xml");
    		List nameList = XPath.selectNodes(doc, "//book[author='Neal Stephenson']/title/text()");
    		for (int i = 0; i < nameList.size(); i++) {
    			System.out.println(((Text)nameList.get(i)).getValue());
    		}
    	}
    Quote Originally Posted by eRaaaa View Post
    In your XPath you are selecting text() and the end, so iter.next() will return a Text-object, not an element, looking at my code!
    I am still learining this so please excuse the dumb questions :)
    The above code was based on the example @ Note to self: parse xml with JDOM and Xpath

Similar Threads

  1. Replies: 0
    Last Post: 05-12-2010, 11:11 AM
  2. Problems with parsing using XPath
    By thooom in forum XML
    Replies: 6
    Last Post: 04-26-2010, 09:47 AM
  3. Problems with XPath (XML Parsing)
    By thooom in forum New To Java
    Replies: 6
    Last Post: 04-25-2010, 04:56 PM
  4. Replies: 0
    Last Post: 11-13-2009, 09:51 PM
  5. Replies: 3
    Last Post: 09-11-2008, 03:00 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •