2013-04-14 5 views
3

JAXB를 사용하여 이름, 스테이션 ID, 위도/경도 및 URL과 같은 기상 관측소 정보가 포함 된 XML 파일을 구문 분석 할 프로젝트를 진행 중입니다. 지금 나는 기상 관측소를 이름으로 만 인쇄하여 모든 것을 시험 할 생각입니다. 내 코드를 디버깅했지만 실행하려고하면 다음 오류가 발생합니다.JAXB XML 구문 분석 문제

스레드 "main"의 예외 javax.xml.bind.UnmarshalException : 예기치 않은 요소 (uri : "", 로컬 : "wx_station_index") . 예상되는 요소는 (없음)

설명이 있습니까? 어떤 도움을 주시면 감사하겠습니다. 내 코드와 XML의 샘플은 아래에 게시되어 있습니다 :

//create criteria for weather station info 
@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class StationTest { 

/** 
* @param args 
*/ 

@XmlElement(name = "station_id") 
String station_id; 

@XmlElement(name = "state") 
String state; 

@XmlElement(name = "station_name") 
String stationName; 

@XmlElement(name = "latitude") 
double latitude; 

@XmlElement(name = "longitude") 
double longitude; 

@XmlElement(name = "html_url") 
String htmlUrl; 

public String getStationID(){ 
    return station_id; 
} 

public void setStationId(String station_id) 
{ 
    this.station_id = station_id; 
} 

public String getState(){ 
    return state; 
} 

public void setState(String state) 
{ 
    this.state = state; 
} 

public String getStationName(){ 
    return stationName; 
} 

public void setStationName(String station_name) 
{ 
    this.stationName = stationName; 
} 

public double getLatitude(){ 
    return latitude; 
} 

public void setLatitude(double latitude) 
{ 
    this.latitude = latitude; 
} 

public double getLongitude(){ 
    return longitude; 
} 

public void setLongitude(double longitude) 
{ 
    this.longitude = longitude; 
} 

public String getUrl(){ 
    return htmlUrl; 
} 

public void setUrl(String url){ 
    this.htmlUrl = htmlUrl; 

} 

} 수입 인 java.util.ArrayList; 그 wx_station_index 오타없는 가정

<?xml version="1.0" encoding="UTF-8"?> 
<wx_station_index> 
    <credit>NOAA's National Weather Service</credit> 
    <credit_URL>http://weather.gov/</credit_URL> 
    <image> 
      <url>http://weather.gov/images/xml_logo.gif</url> 
      <title>NOAA's National Weather Service</title> 
      <link>http://weather.gov</link> 
    </image> 
    <suggested_pickup>08:00 EST</suggested_pickup> 
    <suggested_pickup_period>1140</suggested_pickup_period> 

<station> 
    <station_id>NFNA</station_id> 
    <state>FJ</state> 
    <station_name>Nausori</station_name> 
    <latitude>-18.05</latitude> 
    <longitude>178.567</longitude> 
    <html_url>http://weather.noaa.gov/weather/current/NFNA.html</html_url> 
    <rss_url>http://weather.gov/xml/current_obs/NFNA.rss</rss_url> 
    <xml_url>http://weather.gov/xml/current_obs/NFNA.xml</xml_url> 
</station> 

<station> 
    <station_id>KCEW</station_id> 
    <state>FL</state> 
      <station_name>Crestview, Sikes Airport</station_name> 
    <latitude>30.79</latitude> 
    <longitude>-86.52</longitude> 
      <html_url>http://weather.noaa.gov/weather/current/KCEW.html</html_url> 
      <rss_url>http://weather.gov/xml/current_obs/KCEW.rss</rss_url> 
      <xml_url>http://weather.gov/xml/current_obs/KCEW.xml</xml_url> 
</station> 
+0

당신은 실제 XML을 제공 할 수 있습니다하시기 바랍니다. – 3xil3

+0

그냥 내 XML을 추가했습니다. – David

+0

복사본 붙여 넣기 오류이거나 의도적으로 의도 한 것이 확실하지 않지만 가 닫히지 않았습니다. 이것이 의도적으로라면, 이것은 우리가 스테이션 요소를 찾을 것으로 예상되는 wx_station_index 요소를 기대한다는 것을 의미합니다. 귀하의 자바 코드에서, 우리는 역의 목록을 처리하고 있습니다 (역 요소가 있다면 거기에 맞을 것입니다) – 3xil3

답변

2

: 요청에 따라

import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 
import javax.xml.bind.annotation.XmlSeeAlso; 
import javax.xml.bind.annotation.XmlAccessType; 

//create list for all weather stations 

@XmlRootElement 
@XmlSeeAlso(value = StationTest.class) 
@XmlAccessorType(XmlAccessType.FIELD) 
public class StationListTest { 

/** 
* @param args 
*/ 
@XmlElement(name = "station") 
private ArrayList<StationTest> stationList; 

public void setStationListTest(ArrayList<StationTest> StationList){ 
    this.stationList = StationList; 
} 

public ArrayList<StationTest> getStationListTest(){ 
    return stationList; 
} 

} 

import java.util.ArrayList; 

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.JAXBException; 
import javax.xml.bind.Unmarshaller; 

import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.util.ArrayList; 

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.JAXBException; 
import javax.xml.bind.Unmarshaller; 

//final Test of JAXB 
public class Test3 { 

/** 
* @param args 
*/ 
//read xml 
private static final String STATION_XML = "src/flwxindex3.xml"; 

//main method 
public static void main(String[] args) throws InterruptedException, JAXBException, FileNotFoundException { 

    //create list object 
    ArrayList<StationTest> StationList = new ArrayList<StationTest>(); 

    final JAXBContext jaxbc = JAXBContext.newInstance(StationListTest.class); 
    final Unmarshaller unmarshaller = jaxbc.createUnmarshaller(); 

    //create list for iteration, then iterate printing by name only 
    StationListTest stationListTest = (StationListTest) unmarshaller.unmarshal(new FileReader(STATION_XML)); 
    ArrayList<StationTest> list = stationListTest.getStationListTest(); 
    //final StationListTest stations = (StationListTest) unmarshaller.unmarshal(Thread.currentThread().getContextClassLoader().getResource("src/flwxindex3.xml")); 
    for (final StationTest station : list) { 
     System.out.println(station.getStationName()); 
    } 
} 

}

실제 XML은 (생각 나는 미안 그것을 포함).

jaxb에게 XML의 어느 부분을 코드의 어떤 부분에 매핑할지 지정하기 위해 몇 가지 특수 효과를 추가했습니다. StationListTest를 다음과 같이 변경하면 훨씬 더 잘 작동합니다.

import java.util.ArrayList; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

//create list for all weather stations 
@XmlRootElement(name="wx_station_index") 
public class StationListTest { 

/** 
* @param args 
*/ 
@XmlElement(name="station")  
private ArrayList<StationTest> StationList; 

public StationListTest(){ 
    StationList=new ArrayList<StationTest>(); 
} 

public void setStationListTest(ArrayList<StationTest> StationList){ 
    this.StationList = StationList; 
} 

public ArrayList<StationTest> getStationListTest(){ 
    return StationList; 
} 

} 
+0

안녕하세요. 도와 주셔서 감사합니다. 코드가 작동 중입니다. – David

1

는 클래스 StationListTest에 지정된 프로퍼티 StationList 사이에 불일치와 XML 문서의 암시 station 목록 속성이 있습니다.

@XmlElement(name = "station") 
private ArrayList<StationTest> StationList; 

다른 어떤 빠르게 메모 :

  • 당신은 자바 패턴 (낙타 경우) 이름 따라야 클래스에 대한이 명시 적으로 StationList 속성에서 채워 당신의 XML의 어떤 요소를 정의하여 해결해야 변수 이름. 따라서 StationListstationList이어야합니다.
  • 일반적으로 모든 최상위 데이터 클래스에 @XMLRootElement으로 주석을 추가해야합니다.
  • 일반적으로 Java 클래스를 정의 할 때 가장 일반적인 형식의 형식을 사용해야합니다 (ArrayList 대신 List).
  • 당신은 다른 클래스 다음의 클래스 정의가 XML로 작업 @XmlSeeAlso

로 매핑에 관여하는 표시해야합니다 :

@XmlRootElement(name = "station") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class StationTest { 

    @XmlElement(name = "station_id") 
    String stationId; 

    String state; 

    @XmlElement(name = "station_name") 
    String stationName; 

    double latitude; 
    double longitude; 

    @XmlElement(name = "html_url") 
    String htmlUrl; 

    // Constructor, getters, setters 
} 

@XmlRootElement(name = "wx_station_index") 
@XmlSeeAlso(value = StationTest.class) 
@XmlAccessorType(XmlAccessType.FIELD) 
public class StationListTest { 
    @XmlElement(name = "station") 
    private List<StationTest> stationList; 

    // Constructors, getters, setters 
} 
+0

감사합니다. 한 가지 문제가 있습니다 : '@XmlAccessorType (XmlAccessType.FIELD) '- XMLAccessType을 변수로 해결할 수 없다는 오류가 발생합니다. 내가 주석 처리하고 전체 프로그램을 실행하려고하면 오류가 발생합니다. 스레드 "main"의 예외 javax.xml.bind.UnmarshalException : 예상치 못한 요소 (uri : "", local : "wx_station_index"). 예상되는 요소는 <{} stationListTest>, <{} stationTest> – David

+2

입니다.'javax.xml.bind.annotation.XmlAccessType'을 가져와야합니다. Eclipse를 사용하고 있다면 Ctrl-Shift-o (또는 Mac의 경우 Command-Shift-o)를 눌러 가져 오기를 구성 할 수 있습니다. 다른 IDE에는 비슷한 기능이 있습니다. – Perception

+0

끝난. 하지만 여전히 오류가 발생합니다 : "main"스레드의 예외 javax.xml.bind.UnmarshalException : 예상치 못한 요소 (uri : "", local : "wx_station_index"). 예상되는 요소는 <{} stationListTest>, <{} stationTest> - 모두 감사합니다. – David