简体   繁体   中英

How do I read an XML file with an unbound XML namespace, using JAXB?

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?

Calling JAXBContext.newInstance(); without any arguments doesn't make sense according to the API doc of this method .
You should at least pass the root class:

JAXBContext jaxbContext = JAXBContext.newInstance(SomeObject.class);

After changing this in your Java code the XML file is unmarshalled correctly.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM