[英]How do I read an XML file with an unbound XML namespace, using JAXB?
我正在尝试使用我无法控制的 JAXB 读取 XML 文件。 我无权访问创建此文件的代码。
我创建了这个简化的、可重现的示例。 请注意我需要用来确定要解析到的正确类型的xsi:type
字段,并且java
命名空间未绑定。
<?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>
我创建了这个 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;
}
我尝试使用以下代码(JAXB)读取此文件。 请注意,我当然可以将类型直接传递给newInstance()
,但我需要使用xsi:type
字段。
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());
当我运行此代码时,我收到以下错误:
prefix java is not bound to a namespace
java.lang.IllegalArgumentException: prefix java is not bound to a namespace
如何使用未绑定的java
命名空间将 XML 文件解析为SomeObject
(或任何其他类型),遵守xsi:type
提示?
调用JAXBContext.newInstance();
根据此方法的 API 文档,没有任何 arguments 是没有意义的。
您至少应该通过根 class:
JAXBContext jaxbContext = JAXBContext.newInstance(SomeObject.class);
在您的 Java 代码中更改此内容后,XML 文件被正确解组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.