我收到了 xml
<?xml version="1.0" encoding="UTF-8"?>
<ns1:paymentResponse xmlns:ns1="urn:Brifastservice">
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="tns:paymentAccount_CT_Result">
<message xsi:type="xsd:string">[ERROR] Reference Number Same </message>
<status xsi:type="xsd:string">2007</status>
</return>
</ns1:paymentResponse>
我想解码它,我正在使用下面的代码
JAXBContext jaxbContext = JAXBContext.newInstance(PaymentResponse.class);
Unmarshaller um = jaxbContext.createUnmarshaller();
StringReader resRreader = new StringReader(res);
final SAXParserFactory sax = SAXParserFactory.newInstance();
sax.setNamespaceAware(true);
final XMLReader reader = sax.newSAXParser().getXMLReader();
final Source er = new SAXSource(reader, new InputSource(resRreader));
PaymentResponse response = (PaymentResponse)um.unmarshal(er);
return response.getReturnResponse().getMessage();
但我遇到了异常(exception)
prefix xsd is not bound to a namespace
如果我使用
sax.setNamespaceAware(false);
然后我得到
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"ns1:paymentResponse"). Expected elements are <{urn:someService}paymentResponse>
请建议如何解码?我有包裹信息
@javax.xml.bind.annotation.XmlSchema(
namespace = "urn:someService",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
最佳答案
XML 文档使用 XSI 来声明元素的 XSD 类型,但 XSD 命名空间未在该文档内的任何位置定义。
一个快速但肮脏的解决方案是使用收到的 XML 文档修改字符串并强制添加 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
声明在解析之前在根元素中。
正确的解决方案是创建一个自定义 ContentHandler 来拦截 startDocument
、endDocument
、startPrefixMapping
和 endPrefixMapping
事件并利用 NamespaceSupport
对象来跟踪声明的命名空间并注入(inject)缺少的 XSD 命名空间。可以在使用 Java 处理 XML 的接收命名空间映射一章中找到此示例(减去注入(inject)的命名空间),可在线获取:http://www.cafeconleche.org/books/xmljava/chapters/ch06s09.html .
关于java - 如何跳过 XSD :type while unmarshalling?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40233553/