2013-11-28 49 views
2

我使用JAXB解析器來轉換XML文件,Java對象和我得到異常:Java的解組異常

在線程異常「主要」 javax.xml.bind.UnmarshalException:意外的元素(URI:」 「,地方:」收費「)。預期的元素是< {} service>,< {} servicemethod>,< {} userclass>

我已經將註釋@XmlRootElement包括到類中,但它沒有幫助。

XML文件

<charges> 
<userclass> 
    <classname>adhoc</classname> 
    <service> 
     <serviceclass>local</serviceclass> 
     <servicemethod charge="0.05">call</servicemethod> 
     <servicemethod charge="0.02">text</servicemethod> 
    </service> 
</userclass> 
<userclass> 
    <classname>prepaid</classname> 
    <service> 
     <serviceclass>longdistance</serviceclass> 
     <servicemethod charge="0.05">call</servicemethod> 
     <servicemethod charge="0.02">text</servicemethod> 
    </service> 
    <service> 
     <serviceclass>international</serviceclass> 
     <servicemethod charge="0.25">call</servicemethod> 
     <servicemethod charge="0.10">text</servicemethod> 
    </service> 
    <service> 
     <serviceclass>local</serviceclass> 
     <servicemethod charge="0.01">call</servicemethod> 
     <servicemethod charge="0.01">text</servicemethod> 
    </service> 
</userclass> 
<userclass> 
    <classname>monthly</classname> 
    <service> 
     <serviceclass>longdistance</serviceclass> 
     <servicemethod charge="0.03">call</servicemethod> 
     <servicemethod>text</servicemethod> 
    </service> 
    <service> 
     <serviceclass>international</serviceclass> 
     <servicemethod charge="0.05">call</servicemethod> 
     <servicemethod>text</servicemethod> 
    </service> 
    <service> 
     <serviceclass>local</serviceclass> 
     <servicemethod>call</servicemethod> 
     <servicemethod>text</servicemethod> 
    </service> 
</userclass> 
</charges> 

收費類

import java.util.ArrayList; 
import java.util.List; 

import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlRootElement; 
import javax.xml.bind.annotation.XmlType; 


@XmlAccessorType (XmlAccessType.FIELD) 
@XmlType(name = "", propOrder = {"userclass"}, factoryClass=ObjectFactory.class, factoryMethod="createChargers") 
@XmlRootElement(name="charges", namespace="") 
public class Charges { 
    List<Userclass> userclass; 

    public List<Userclass> getUserClasses() { 
     if (userclass == null) { 
      userclass = new ArrayList<Userclass>(); 
     } 
     return this.userclass; 
    } 
} 

如果有人能告訴我,我要去哪裏錯了,它會非常感謝!

回答

1

您可能忘記在用於引導JAXBContext的類中包含Charges。嘗試編組一個Charges的實例以查看會發生什麼。

+0

我試過編組充電的一個實例,但我得到了同樣的異常。 – alereis

+0

@alereis - 如果'marshal'失敗,你應該得到'MarshalException'。 –