问题
需要生成多层嵌套xml,类似如下内容:
<A><B><C><!-- C类的字段 --></C><C><!-- 另一个C类的字段 --></C></B>
</A>
解决
C.java
import jakarta.xml.bind.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
public class C {@XmlElement(nillable = true)private String field1;@XmlElement(nillable = true)private String field2;
}
这里使用到了lombok。注意这里需要设置@XmlAccessorType(XmlAccessType.FIELD)
不然会出现:JAXB IllegalAnnotationException is thrown during parsing XML
错误。
B.java
import jakarta.xml.bind.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
public class B {@XmlElement(name = "C") // 指定 XML 标签名称private List<C> cList;
}
这里设置了一个数组标签。
A.java
import jakarta.xml.bind.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class A {@XmlElement(name = "B") // 指定 XML 标签名称private B b;
}
这里是根xml,所以,这里需要设置@XmlRootElement
注解。
使用
...StringWriter xmlWriter = new StringWriter();marshaller.marshal(uniteWorkReq, new StreamResult(xmlWriter));String xml = xmlWriter.toString();...
配置,依旧是如下方式注入:
@Beanpublic Jaxb2Marshaller marshaller() {Jaxb2Marshaller marshaller = new Jaxb2Marshaller();// this package must match the package in the <generatePackage> specified in// pom.xml
// marshaller.setContextPath("com.cmdi.system.wsdl");marshaller.setPackagesToScan("com.xxx.xxxx.wsdl");return marshaller;}
参考
- JAXB IllegalAnnotationException is thrown during parsing XML