2

找人看我的简单代码。我对我正在做的事情相当陌生,并且知道我可能只是在某个地方犯了一个简单的错误。

我正在解析一个通过 http 的 xml 文件,并尝试将与元素关联的文本打印到屏幕上,并创建一个由这些元素中的文本填充的对象。

我可以打印所有元素和相关文本,但对象的字段中都有一个空值。如果我有什么需要更好地解释的,请告诉我。

代码如下:

对象等级:

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

}

这是具有方法和主要的类:

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

}

}
4

4 回答 4

4

你的构造函数什么也没做!

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;
  ...
}

但更好的是使用 Java XML Binding jaxb。它会自动将 java 类映射到 xml

于 2012-12-19T17:27:12.113 回答
3

看看 Jaxb 库。它可以为您完成所有繁重的工作。

JAXB 主页

沃杰拉教程

Mkyong教程

于 2012-12-19T19:18:27.080 回答
1

将传递给StageOfLife构造函数的值设置为变量。

于 2012-12-19T17:28:57.227 回答
0

试试这个

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

    }
于 2012-12-19T17:40:49.503 回答