我正在尝试编写Java 11 XML解组器,该模型在将名称空间数据转换为对象之前会剥离该名称空间数据,但是出现以下错误。该应用需要先从所有元素中删除previous app:
,然后才能投射到Object。
如何使用JDK11做到这一点?
错误
javax.xml.bind.UnmarshalException
- with linked exception:
[com.sun.istack.SAXParseException2; lineNumber: 2; columnNumber: 67; unexpected element (uri:"", local:"app:exampleXML"). Expected elements are <{http://www.example.com/schemas/app}object>]
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:453)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:387)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:356)
XmlUnmarshaller.unmarshal(XmlUnmarshaller.java:36)
...
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.sun.istack.SAXParseException2; lineNumber: 2; columnNumber: 67; unexpected element (uri:"", local:"app:exampleXML"). Expected elements are <{http://www.example.com/schemas/app}object>
...
... 20 more
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"app:exampleXML"). Expected elements are <{http://www.example.com/schemas/app}object>
... 31 more
Test
public void testUnmarshal() throws JAXBException, XMLStreamException {
String xml3 = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<app:exampleXML xmlns:app=\"http://www.example.com/schemas/app\">\n" +
"<app:id>app-id</app:id>\n" +
"<app:time>2020-06-05T13:17:00.899Z</app:time>\n" +
"<app:type>test</app:type>\n" +
"<app:description>Test</app:description>\n" +
"</app:exampleXML>";
XmlUnmarshaller unmarshaller = new XmlUnmarshaller();
Object object = unmarshaller.unmarshal(xml3, Object.class);
System.out.println(object);
}
Unmarshaller
public <T> T unmarshal(String xml, Class<T> clazz) throws JAXBException, XMLStreamException {
JAXBContext jc = JAXBContext.newInstance(clazz);
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
StreamSource source = new StreamSource(new StringReader(xml));
XMLStreamReader xsr = xif.createXMLStreamReader(source);
return clazz.cast(unmarshaller.unmarshal(xsr));
}
Object
@XmlRootElement(name = "exampleXML", namespace="http://www.example.com/schemas/app")
@XmlAccessorType(XmlAccessType.FIELD)
public class XML {
public static final int DESCRIPTION_LENGTH = 4000;
@XmlElement(name = "id", required = true)
private String id;
@XmlElement(name = "time", required = true)
@XmlJavaTypeAdapter(InstantXmlAdapter.class)
@JsonSerialize(using = InstantJsonSerializer.class)
@JsonDeserialize(using = InstantJsonDeserializer.class)
private Instant time;
@XmlElement(name = "type", required = true)
private CheckpointLevel type;
@XmlElement(name = "description")
@XmlJavaTypeAdapter(CDATAXmlAdapter.class)
private String description;
已将package-info.java