仅解组
如果您只是在进行解组,那么您可以使用 aStreamReaderDelegate
去除数字后缀。
演示
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.stream.util.StreamReaderDelegate;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(HotelRoomDetails.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource("src/forum19834756/input.xml"));
xsr = new StreamReaderDelegate(xsr) {
@Override
public String getLocalName() {
String localName = super.getLocalName();
if(localName.startsWith("Night") && !localName.equals("NightRates")) {
return "Night";
}
return localName;
}
};
Unmarshaller unmarshaller = jc.createUnmarshaller();
HotelRoomDetails details = (HotelRoomDetails) unmarshaller.unmarshal(xsr);
System.out.println(details.getNightRates().size());
}
}
酒店客房详情
Then you have a collection property that maps to the element called Night
.
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class HotelRoomDetails {
private List<String> nightRates = new ArrayList<String>();
@XmlElementWrapper(name = "NightRates")
@XmlElement(name = "Night")
public List<String> getNightRates() {
return nightRates;
}
}
Unmarshal & Marshal
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
If you need to support reading and writing to this format you could use MOXy's @XmlVariableNode
extension.