Mike
Mike

Reputation: 1610

Need help extracting XML element values and depositing them into a map or other type of collection in Java

The below code prints the element contents of my XML file, however, for the life of me I have been unsuccessful at extracting the element values and putting them in a map or other type of array or list. Any help would be greatly appreciated!!!!

  public class client
  {
     public static void main(String[] args )
     {
        int length = 0;
        String [] array;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {

           //Using factory get an instance of document builder
           DocumentBuilder builder  = factory.newDocumentBuilder();

           //create the document by parsing the actual file
           Document doc = builder.parse(new File ("server.xml"));

           //creat an XPath to be used in the extraction of the nodes
           XPathFactory xPFactory = XPathFactory.newInstance();
           XPath path = xPFactory.newXPath();

           //Extract ports
           XPathExpression portExpr
            = path.compile("//configuration/hostInfo/port");

           //Extract hosts
           XPathExpression hostExpr
            = path.compile("//configuration/hostInfo/host");

           Object pResult = portExpr.evaluate(doc, XPathConstants.NODESET);
           Object hResult = hostExpr.evaluate(doc, XPathConstants.NODESET);
           NodeList pNodes = (NodeList) pResult;
           NodeList hNodes = (NodeList) hResult;
           array = new String [(pNodes.getLength())*2];

           array = populateArray(array, pNodes, hNodes);
           for (int k = 0; k < array.length; k++)
               System.out.println( k+ "="+ array[k]);

        }catch (Exception e) {
           e.printStackTrace();
     }
  }

  public static String[] populateArray (String array[], NodeList pNodes, NodeList hNodes){

        array[0]=pNodes.item(0).getTextContent();
        array[1]=hNodes.item(1).getTextContent();

        for (int i = 1; i < pNodes.getLength(); i++){
           array[2*i]= pNodes.item(i).getTextContent();
           array[(2*i)+1]= hNodes.item(i).getTextContent();
        }
        return array;
     }

  }

XML FILE

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>
   <hostInfo>
     <port>8189</port>
     <host>localhost</host>    
   </hostInfo>
   <hostInfo>
     <port>8190</port>
     <host>localhost</host>
   </hostInfo>
   <hostInfo>
     <port>8191</port>
     <host>localhost</host>
   </hostInfo>  
 </configuration>

Upvotes: 0

Views: 212

Answers (1)

bluefoot
bluefoot

Reputation: 10580

You can do path.compile that will return a XPathExpression object. Then you can call evaluate to get an array of NodeList.

Take a look at http://www.ibm.com/developerworks/library/x-javaxpathapi.html and http://download.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/package-summary.html .

Upvotes: 3

Related Questions