简体   繁体   English

如何告诉JAXB,该元素是“根之子”?

[英]How to tell JAXB that, the element is a Child of the Root?

I have some test data in XML format, that I want to map to POJO. 我有一些XML格式的测试数据,我想映射到POJO。

<Root>
   <Child1>
      <Data>
      </Data>
   </Child1>
   <Child2>
      <Data>
      </Data>
   </Child2>
</Root>

Child1 is the first Object and Child2 the second. Child1是第一个对象,Child2是第二个对象。

JAXBContext context = JAXBContext.newInstance(classesToLoad);
Unmarshaller um = context.createUnmarshaller();
Object obj = (Object) um.unmarshal(data);

Object in this case is just a placeholder 在这种情况下, 对象只是一个占位符

@Getter
@Setter
@XmlRootElement(name = "TestData")
public class Child1 {

    @XmlElement(name = "ID")
    private String ID;
}

.

This is the code I'm working with right now, but I get this exception: 这是我现在正在使用的代码,但是出现了这个异常:

javax.xml.bind.UnmarshalException: unexpected Element (URI:"", lokal:"TestData"). javax.xml.bind.UnmarshalException:意外元素(URI:“”,lokal:“ TestData”)。 expectected elements are: Child1 预期的元素是:Child1

Move the annotation 移动注释

@XmlRootElement(name = "TestData")

To your Root class and change it to 转到您的Root类并将其更改为

@XmlRootElement(name = "Root")

And I believe you'll need 我相信你会需要

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Child1")

in the Child1 class. 在Child1类中。

And give it a go again. 再试一次。

What the exception tells you is it's expecting an element of name TestData with namespace "" (you can ignore namespace for now since it's blank, but take minute or two to have a look at this since it's something that can trip you up when working with XML for the first time), and it's because you define the root element as TestData. 什么异常告诉你的是它的预期名称TESTDATA的元素命名空间“”(你可以忽略命名空间,因为现在它是空白的,但需要两分钟来看看这个 ,因为它的东西,可以工作时,你绊倒第一次使用XML),这是因为您将根元素定义为TestData。

Additionally, the data example you've provided does not seem to correspond to your designed class. 此外,您提供的数据示例似乎与您设计的类不对应。

<Child1>
    <Data>
    </Data>
</Child1>

public class Child1 {

    @XmlElement(name = "ID")
    private String ID;
}

I don't know if you've replaced the enclosed data for brevity for the sake of a neater question, but your Java object would more closely resemble this XML. 我不知道为了简洁起见,是否为了简洁而替换了封闭的数据,但是您的Java对象将更类似于该XML。

<Child1>
   <ID>[String ID value]</ID>
</Child1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM