为了账号安全,请及时绑定邮箱和手机立即绑定

通过使用 JAXB 通过取消编组将 XML 转换为对象

通过使用 JAXB 通过取消编组将 XML 转换为对象

红颜莎娜 2022-08-03 15:08:59
我想通过使用JAXB取消编组将XML转换为java。这是我的员工.xml。我试图转换,但它显示错误javax.xml.bind.UnmarshalException<?xml version="1.0" encoding="UTF-8"?><deptname name="Research"> <employee>    <eid>r-001</eid>    <ename>Dinesh R</ename>    <age>35</age>    <deptcode>d1</deptcode>    <deptname>Research</deptname>    <salary>20000</salary></employee></deptname><deptname name="Sales"><employee>    <eid>s-001</eid>    <ename>Kanmani S</ename>    <age>35</age>    <deptcode>d2</deptcode>    <deptname>Sales</deptname>    <salary>30000</salary>   </employee>  </deptname><deptname name="Delivery">  <employee>    <eid>d-001</eid>    <ename>Kanchana M</ename>    <age>35</age>    <deptcode>d3</deptcode>    <deptname>Delivery</deptname>    <salary>20000</salary></employee>  </deptname>
查看完整描述

1 回答

?
www说

TA贡献1775条经验 获得超8个赞

根据 XML 文档,您只能有一个根元素,因此应将 xml 更改为:


<?xml version="1.0" encoding="UTF-8"?>

<departments>

    <deptname name="Research">

        <employee>

            <eid>r-001</eid>

            <ename>Dinesh R</ename>

            <age>35</age>

            <deptcode>d1</deptcode>

            <deptname>Research</deptname>

            <salary>20000</salary>

        </employee>

    </deptname>

    <deptname name="Sales">

        <employee>

            <eid>s-001</eid>

            <ename>Kanmani S</ename>

            <age>35</age>

            <deptcode>d2</deptcode>

            <deptname>Sales</deptname>

            <salary>30000</salary>

        </employee>

    </deptname>

    <deptname name="Delivery">

        <employee>

            <eid>d-001</eid>

            <ename>Kanchana M</ename>

            <age>35</age>

            <deptcode>d3</deptcode>

            <deptname>Delivery</deptname>

            <salary>20000</salary>

        </employee>

    </deptname>

</departments>

然后,您需要一个类部门来阅读该文章:


@XmlRootElement(name="departments")

public class Departments {

  List<Department> deptname;


  // Getters and setters

}

测试用例是:


@Test

  public void testXML() {

    try {

      File file = new File("./src/main/resources/employee.xml");

      JAXBContext jaxbContext = JAXBContext.newInstance(Departments.class);


      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

      Departments departments = (Departments) jaxbUnmarshaller.unmarshal(file);

      System.out.println(departments);

    } catch (JAXBException e) {

      e.printStackTrace();

    }

  }

其次,您没有“研究”或“销售”或“交付”属性,您有一个可以采用任何字符串值的属性“name”,因此您需要更改实现:


public class Department {

  @XmlAttribute(name = "name")

  private String name;


  @XmlElement(name = "employee")

  private List<Employee> employee = new ArrayList<>();


  // Getters and setters

}


查看完整回答
反对 回复 2022-08-03
  • 1 回答
  • 0 关注
  • 64 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信