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);

   }

}

Reply via email to