I am trying to read a XML file using JAXB that I don't have control over. I do not have access to the code that creates this file.
I created this simplified, reproducible example. Note the xsi:type
field that I need to use to determine the correct type to parse to and it the java
namespace is not bound.
<?xml version="1.0" encoding="UTF-8"?>
<someObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="java:com.group.module.SomeObject">
<field>value</field>
</someObject>
I created this class:
package com.group.module;
import lombok.Getter;
import lombok.Setter;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@Setter
@Getter
public class SomeObject {
private String field;
}
I try to read this file using the following code (JAXB). Note that I could of course pass the type directly to newInstance()
, but I need to use the xsi:type
field.
File f = new File("file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance();
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
SomeObject obj = (SomeObject) jaxbUnmarshaller.unmarshal(f);
System.out.println(obj.getField());
When I run this code, I get the following error:
prefix java is not bound to a namespace
java.lang.IllegalArgumentException: prefix java is not bound to a namespace
How can I parse the XML file into SomeObject
(or any other type), honoring the xsi:type
hint, with an unbound java
namespace?