有几种方法可以支持这个用例:
选项 #1 - 任何 JAXB (JSR-222) 实现
如果您只需要读取 XML 到对象,那么您可以利用 aStreamReaderDelegate
并执行以下操作。基本上它使坏的 XML 看起来好像是好的 XML:
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 {
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource("src/forum16529016/input.xml"));
xsr = new StreamReaderDelegate(xsr) {
@Override
public String getLocalName() {
String localName = super.getLocalName();
if(!"Property".equals(localName) && super.getEventType() == XMLStreamReader.START_ELEMENT) {
return localName;
}
if(super.getEventType() == XMLStreamReader.START_ELEMENT) {
return super.getAttributeValue(null, "name");
}
return localName;
}
};
JAXBContext jc = JAXBContext.newInstance(ActualType.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
ActualType actualType = unmarshaller.unmarshal(xsr, ActualType.class).getValue();
System.out.println(actualType.prop1);
System.out.println(actualType.prop2);
}
}
选项 #2 - EclipseLink JAXB(MOXy 的)@XmlPath 扩展
注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。
MOXy 有一个@XmlPath
扩展,可让您映射此用例。
import javax.xml.bind.annotation.XmlType;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlType(name="actualType")
public class ActualType
{
@XmlPath("Property[@name='prop1']/text())
public X prop1
@XmlPath("Property[@name='prop1']/text())
public Y prop2
}
了解更多信息