2012-12-19 4 views
2

내 간단한 코드를 살펴볼 사람을 찾고 있습니다. 나는 내가하고있는 일에 오히려 새로운 것이며 아마 어딘가에서 단순한 실수를하고 있음을 알고있다.XML 파싱 및 객체 자바 만들기

http를 초과하는 xml 파일을 구문 분석하고 해당 요소와 관련된 텍스트를 화면에 인쇄하고 해당 요소의 텍스트로 채워진 개체를 만들려고합니다.

모든 요소와 관련 텍스트를 인쇄 할 수 있지만 개체의 필드에는 모두 null 값이 있습니다. 만약 내가 더 잘 설명해야 할 필요가 있다면 알려줘.

객체 클래스 :

코드는 아래에서 발견되는 생성자는 아무것도되지

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

Vogella Tutorial

JAXB Homepage

이 문제를 반복 가능한 가장 작은 프로그램이 감소 해주십시오. – Woot4Moo

+0

'StageOfLife'는 현재 상태로 컴파일되지 않습니다. – BunjiquoBianco

답변

4

: 여기

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

} 

을 그리고 방법과 주요 가지는 클래스입니다!

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 바인딩 jaxb를 사용하는 것이 훨씬 더 좋습니다. Java 클래스를 xml에 자동으로 매핑합니다.

+0

와우 ... 나는 그것을 간과했다고 믿을 수 없다. 나는 논리가 잘못되어 기본 클래스를 보지 않고 있다고 너무 바빴다. 고맙습니다! – parchambeau

1

StageOfLife 생성자에 전달할 값을 변수로 설정합니다.

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

    } 
3

는 JAXB 라이브러리를 살펴 보자보십시오. 그것은 당신을 위해 모든 무거운 짐을 다 할 수 있습니다.

Mkyong Tutorial