你可以在 Response (root) class 上做这样的事情:
@XmlRootElement(name = "Response")
@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElements(value = {
@XmlElement(name = "Field1", type = Field.class),
@XmlElement(name = "Field2", type = Field.class),
@XmlElement(name = "Field3", type = Field.class)
})
private Field field;
}
只要遇到不同的FIelds,JAXB 就会自动映射到字段类。
编辑/更新
XML:
<Response>
<Field1>
<Name>abc</Name>
<Id>1</Id>
</Field1>
<Field2>
<Name>sdf</Name>
<Id>2</Id>
</Field2>
<Field3>
<Name>xyz</Name>
<Id>3</Id>
</Field3>
</Response>
根:
@XmlRootElement(name = "Response")
@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlAnyElement
private List<Field> action;
}
字段:
@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Field {
private String Name;
private String Id;
}
主要:
public class Main {
public static void main(String[] args) throws JAXBException, XMLStreamException {
final InputStream inputStream = Main.class.getClassLoader().getResourceAsStream("sample.xml");
final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
final Unmarshaller unmarshaller = JAXBContext.newInstance(Root.class).createUnmarshaller();
final Root root = unmarshaller.unmarshal(xmlStreamReader, Root.class).getValue();
System.out.println(root.toString());
Marshaller marshaller = JAXBContext.newInstance(Root.class).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(root, System.out);
}
}
输出:
Root(action=[[Field1: null], [Field2: null], [Field3: null]])
<Response>
<Field1>
<Name>abc</Name>
<Id>1</Id>
</Field1>
<Field2>
<Name>sdf</Name>
<Id>2</Id>
</Field2>
<Field3>
<Name>xyz</Name>
<Id>3</Id>
</Field3>
</Response>