【问题标题】:how to skip XSD:type while unmarshalling?如何在解组时跳过 XSD:type?
【发布时间】:2016-10-25 07:11:15
【问题描述】:

我收到了 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();

但我遇到了异常

前缀 xsd 未绑定到命名空间

如果我使用

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)

【问题讨论】:

    标签: java xml jaxb xml-namespaces


    【解决方案1】:

    XML 文档使用 XSI 来声明元素的 XSD 类型,但 XSD 命名空间并未在该文档内的任何地方定义。

    一个快速而肮脏的解决方案是使用接收到的 XML 文档修改字符串,并在解析之前在根元素中强制添加 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 声明。

    正确的解决方案是创建一个自定义 ContentHandler 来拦截 startDocumentendDocumentstartPrefixMappingendPrefixMapping 事件并使用 NamespaceSupport 对象来跟踪声明的命名空间并注入缺少 XSD 命名空间。这方面的一个例子(减去注入的命名空间)可以在 Processing XML with JavaReceiving Namespace Mappings 一章中找到,可在 http://www.cafeconleche.org/books/xmljava/chapters/ch06s09.html 在线获取。

    【讨论】:

      猜你喜欢
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 2018-11-17
      • 2014-06-03
      • 1970-01-01
      • 2012-02-09
      • 2011-01-24
      相关资源
      最近更新 更多