Hi Jeff,
 
I couldn't test it out, but I think there is something wrong with your xpath.
 
Node node2 = document.selectSingleNode("//TestA/test[2]");
 
This will select the second test element: node2 = <test>2</test>
 
String data2 = node2.valueOf("test");
 
This will select the value of the test child-element of node2, but node2 doesn't have child elements, so this cannot return "2". I think the following should work (couldn't test it myself over here though)
 
String data2 = node2.valueOf(".");
or
String data2 = node2.getStringValue();

Did this solve your problem?

regards,
Maarten

"Grove, Jeff" <[EMAIL PROTECTED]> wrote:

I can get data from a Node that contains multiple elements but I can’t get data from a node that contains a single element. Am I missing some basic concept here?

 

/**

 * Sample Test Document (test.xml) located in C:\

 *

 * <DOCUMENT>

 *   <TestA>

 *     <test>1</test>

 *     <test>2</test>

 *     <test>3</test>

 *   </TestA>

 * </DOCUMENT>

 *

 */

 

import java.net.MalformedURLException;

import java.net.URL;

 

import  org.dom4j.*;

import org.dom4j.io.SAXReader;

 

public class XMLTest

{

   private static Document document;

  

   public static void main(String[] args)

   {

      /////////////////////////////////////////////////////////

      // Read Document (works, reads document)

      /////////////////////////////////////////////////////////

      try

      {

            URL filelocation = new URL("file:///C:/test.xml");

            SAXReader reader = new SAXReader();

            document = reader.read(filelocation);                

      }

      catch (DocumentException de)

      {

            System.out.println("Error: " + de);

      }

      catch (MalformedURLException mue)

      {

            System.out.println("Error: " + mue);

      }

     

           

      /////////////////////////////////////////////////////////

      // get a node from the document (works, gets node & data)

      /////////////////////////////////////////////////////////

      Node nodeA = document.selectSingleNode("//TestA");

      System.out.println("Node A:\n  " + nodeA.asXML());

           

      // get data from node

      String dataA = nodeA.valueOf("test[2]");

      System.out.println("Data test[2]: " + dataA);

                       

      /////////////////////////////////////////////////////////

      // get data from node (FAILS TO FIND DATA IN NODE, WHY?)

      /////////////////////////////////////////////////////////

      Node node2 = document.selectSingleNode("//TestA/test[2]");

      System.out.println("Node 2:\n  " + node2.asXML());

 

      String data2 = node2.valueOf("test");

      System.out.println("Data test: " + data2);

   }

}


Do you Yahoo!?
Meet the all-new My Yahoo! – Try it today!

Reply via email to