Java unmarshaller异常

时间:2013-11-28 22:36:23

标签: java xml jaxb

我正在使用JAXB解析器将XML文件转换为Java对象,我得到了异常:

线程“main”中的异常javax.xml.bind.UnmarshalException:意外元素(uri:“”,local:“charge”)。预期元素为< {} 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 个答案:

答案 0 :(得分:1)

您可能忘记将Charges包含在用于引导JAXBContext的类中。尝试编组Charges的实例,看看会发生什么。