2

Looking for someone to look over my simple code. I am rather new to what I am doing and know that I am probably just making a simple mistake somewhere.

I am parsing an xml file that is over http and trying to print out the text associated with the elements to the screen, and make an object that is populated by the text in those elements.

I can get all of the elements and associated text printed but the objects all have a null value in their fields. Let me know if I anything needs to be explained better.

Code is found below:

Object Class:

   package com.entities;



public class StageOfLife
{

private String endDate;
private String offerData;
private String offerType;
private String redemption;
private String startDate;
private String termsConditions;
private String title;
private String merchantDescription;
private String merchantLogo;
private String merchantName;

public StageOfLife() {

}

public StageOfLife(String endDate, String offerData, String offerType,
        String redemption, String startDate, String termsConditions,
        String title, String merchantDescription, String merchantLogo,
        String merchantName)
{

// Getters Setters HEre

 public String toString() {

 StringBuffer buffer = new StringBuffer();

 buffer.append(endDate);
 buffer.append("\n");
 buffer.append(offerData);
 buffer.append("\n");
 buffer.append(offerType);
 buffer.append("\n");
 buffer.append(redemption);
 buffer.append("\n");
 buffer.append(startDate);
 buffer.append("\n");
 buffer.append(termsConditions);
 buffer.append("\n");
 buffer.append(title);
 buffer.append("\n");
 buffer.append(merchantDescription);
 buffer.append("\n");
 buffer.append(merchantLogo);
 buffer.append("\n");
 buffer.append(merchantName);

 return buffer.toString();
 }

}

And here is is the class with the methods and main:

package com.xmlparse;

import java.io.IOException;
import java.util.ArrayList;
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.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.entities.StageOfLife;



public class XmlParserStage
{
 Document dom;
 DocumentBuilder db;
 List<StageOfLife> myStageList;

 public XmlParserStage(){
        //create a list to hold the StageOfLife objects
        myStageList = new ArrayList<StageOfLife>();
    }


private void parseXmlFile(){
    //get the factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {

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

        //parse to get DOM representation of the XML file
    dom = db.parse("http:/url/goes/here");


    } catch(ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch(SAXException se) {
        se.printStackTrace();
    } catch(IOException ioe) {
        ioe.printStackTrace();
    }
}

 private void parseDocument() {


    //get the root element
    Element docEle = dom.getDocumentElement();

    //get a nodelist of elements
    NodeList nl = docEle.getElementsByTagName("Offer");
    if(nl != null && nl.getLength() > 0) {
        for(int i = 0 ; i < nl.getLength(); i++) {

            //get the elements 
            Element solEl = (Element)nl.item(i);

            //get the StageOfLife object
            StageOfLife sol = getStageOfLife(solEl);

            //add it to list
          myStageList.add(sol);
        }
    }
}

/*
  take an <offer> element and read the values in, create
  an StageOfLife object and return it
*/
private StageOfLife getStageOfLife(Element solEl) {

/*
  for each <offer> element get the values
*/

    String endDate = getTextValue(solEl,"EndDate");
    String offerData = getTextValue(solEl,"OfferData");
    String offerType = getTextValue(solEl,"OfferType");
    String redemption = getTextValue(solEl,"Redemption");
    String startDate = getTextValue(solEl,"StartDate");
    String termsConditions = getTextValue(solEl,"TermsConditions");
    String title = getTextValue(solEl,"Title");
    String merchantDescription = getTextValue(solEl,"MerchantDescription");
    String merchantLogo = getTextValue(solEl,"MerchantLogo");
    String merchantName = getTextValue(solEl,"MerchantName");

    //Create a new StageOfLife object with the value read from the xml nodes
    StageOfLife sol = new StageOfLife(endDate, offerData, offerType,
             redemption, startDate, termsConditions,
             title, merchantDescription, merchantLogo,
             merchantName);

    return sol;
}

/*
  take a xml element and the tag name, look for the tag and get
  the text content
 */

private String getTextValue(Element ele, String tagName) {

    String textVal = null;
    NodeList nl = ele.getElementsByTagName(tagName);
    if(nl != null && nl.getLength() > 0) {
        Element el = (Element)nl.item(0);
        textVal = el.getFirstChild().getNodeValue();

        System.out.print(el + ":" + textVal);
        System.out.println();

    }

    return textVal;
}


/*
 Calls getTextValue and returns a int value
*/
private int getIntValue(Element ele, String tagName) {

    return Integer.parseInt(getTextValue(ele,tagName));
}

private void printData(){

    System.out.println("Number of Offers: '" + myStageList.size() + "'.");

    Iterator it = myStageList.iterator();
    while(it.hasNext()) {
        System.out.println(it.next().toString());

    }
}

public void run() {

    //parse the xml file and get the dom object
    parseXmlFile();

    //get each stageoflife element and create a StageOfLife object
    parseDocument();

    //Iterate through the list and print the data
    printData();
}

public static void main(String [] args) throws ClientProtocolException, IOException      {

  XmlParserStage xmlParser = new XmlParserStage();

    xmlParser.httpClient();

    xmlParser.run(); 

}

}
2
  • 2
    Please reduce this to the smallest program possible that repeats your issue.
    – Woot4Moo
    Dec 19, 2012 at 17:25
  • StageOfLife won't compile in its current state. Dec 19, 2012 at 17:30

4 Answers 4

4

your constructor is not doing anything!

public StageOfLife(String endDate, String offerData, String offerType,
        String redemption, String startDate, String termsConditions,
        String title, String merchantDescription, String merchantLogo,
        String merchantName)
{
  // set the data
  this.endDate = endDate;
  ...
}

But much better is to use Java XML Binding jaxb. it automatically maps java classes to xml

1
  • Wow...I cannot believe I overlooked that. I was so busy thinking that the logic was wrong and was not even looking at the base class. Thank you! Dec 19, 2012 at 17:31
3

Take a look at Jaxb library. It can do all the heavy lifting for you.

JAXB Homepage

Vogella Tutorial

Mkyong Tutorial

1

Set the values you are passing to the StageOfLife constructor to the variables.

0

Try this

public class Tester {

    String getString() throws IOException, ParserConfigurationException, SAXException {
        InputStream inputStream = //your stream from http
        String sa = "";
        int cc;
        while((cc = inputStream.read()) != -1) {
            sa += (char) cc;
        }
        ByteArrayInputStream sr = new ByteArrayInputStream(sa.getBytes());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(sr);

        Node node=doc.getDocumentElement().getFirstChild();
        String data=node.getNodeName();

        return data;
    }

    public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
        Tester t = new Tester();
        System.out.println(t.getString());

    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.