我从 Web 服务接收到以下格式的 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<string xmlns="http://someurl.com">somethingheresomethinghere</string>
我正在尝试将其解码为如下所示的 POJO:
@XmlRootElement(name="string")
public class StringValue {
@XmlValue
private String value;
public StringValue () {
}
}
我的解码代码是这样的:
public T xmlToObject(Class<T> contextPath, Reader reader) throws Exception {
JAXBContext context = JAXBContext.newInstance(contextPath);
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setEventHandler(new XMLValidationEventHandler());
T objectToConvert = (T) unmarshaller.unmarshal(reader);
return objectToConvert;
}
但我收到以下错误:
unexpected element (uri:"http://someurl.com", local:"string"). Expected elements are <{}string>
如果 XML 中的命名空间被省略,那么它会起作用,但我不想改变 XML,而是想知道如何制作它,以便命名空间部分在编码或处理时不会给我带来任何麻烦。使用 JAXB 解码。
我怎样才能实现这种行为?
最佳答案
您可以使用包级别 @XmlSchema
注释来映射命名空间。
@XmlSchema(
namespace = "http://someurl.com",
elementFormDefault = XmlNsForm.QUALIFIED)
package example;
import javax.xml.bind.annotation.*;
了解更多信息
我在我的博客上写了更多有关 JAXB 和 namespace 限定的内容:
关于java - 如何使用 JAXB 映射 XML 忽略命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976746/