有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中解组时发生xml错误

我有一个xml文件已经包含

***<?xml version=“1.0”encoding=“UTF-8”standalone=“是”&燃气轮机

<;客户 id="100">

<;年龄>;22</年龄>

<;名称>;纳文</名称>; </客户>**

我的POJO课程就是为了这个

公共类客户{

String name;
int age;
int id;

public String getName() {
    return name;
}

public int getAge() {
    return age;
}

public int getId() {
    return id;
}

}

我试图通过使用JAXB作为

   File file = new File("sample.txt");
   JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
   Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
   Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
   System.out.println(customer);

但我也有例外

意外元素(uri:,本地:“客户”)。预期元素为(无)

请帮帮我


共 (2) 个答案

  1. # 1 楼答案

    可能有两个问题
    1-纠正xml的格式,我可以在标签中看到空格,比如use,而不是<;使用>;最好使用下面的xml

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <customer id="100">
        <age>22</age>
        <name>naveen</name> 
    </customer>
    

    2-并注释Jaxb类-使用下面的

    @XmlRootElement
    public class Customer {
    @XmlElement
    String name;
    @XmlElement
    int age;
    @XmlAttribute
    int id;
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public int getId() {
        return id;
    }
    }
    
  2. # 2 楼答案

    目前,类中没有足够的信息让JAXB知道基于根元素实例化哪个类。您可以执行以下操作之一:

    1. Customer类上添加@XmlRootElement,以显式地将Customer类映射到customer根元素
    2. 使用采用unmarshal参数的Class方法:

      JAXBElement<Customer> je = unmarshaller.unmarshal(source, Customer.class);
      Customer customer = je.getValue();
      

    了解更多信息