如何将带有 XSD/命名空间的 XML 转换为对象?
我收到此错误:
javax.xml.bind.UnmarshalException:意外元素(uri:“ http://www.opengis.net/wfs/2.0 ”,本地:“FeatureCollection”)。预期的元素是 <{}FeatureCollection>
这是示例 XML:
<wfs:FeatureCollection xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fes="http://www.opengis.net/fes/2.0" xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" numberMatched="7961422" numberReturned="0" timeStamp="2019-07-16T09:44:51.540Z" xsi:schemaLocation="http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd"/>
我的简单 JAXB 转换器是:
public static Object convertXmlToObject(String xmlString, Class targetClass) {
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance( targetClass);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
这个方法的调用是:
TargetObject to = (TargetObject) converter.convertXmlToObject( xmlString, TargetObject.class);
目标对象是:
@XmlRootElement( name="FeatureCollection")
public class TargetObject {
private long numberMatched = -1;
private long numberReturned = -1;
private LocalDateTime timeStamp;
// ... all getters
@XmlAttribute
public void setNumberMatched(long numberMatched) {
this.numberMatched = numberMatched;
}
@XmlAttribute
public void setNumberReturned(long numberReturned) {
this.numberReturned = numberReturned;
}
@XmlAttribute
@XmlJavaTypeAdapter(value = LocalDateTimeAdapter.class)
public void setTimeStamp(LocalDateTime timeStamp) {
this.timeStamp = timeStamp;
}
}
如何改进我的代码以将 XML 字符串转换为对象?
扬帆大鱼
相关分类