JAXB 使用命名空间和前缀解组 [英] JAXB unmarshall with namespaces and prefix

查看:50
本文介绍了JAXB 使用命名空间和前缀解组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JAXB 从 SOAP 响应中解析 xml 元素.我已经为 xml 元素定义了 POJO 类.我已经测试了没有命名空间和前缀的 pojo 类,它的工作正常.尽管当我尝试使用命名空间和前缀进行解析时遇到以下异常.要求是解析来自 SOAPMessage 对象的输入

I am using JAXB to parse xml elements from the SOAP response. I have defined POJO classes for the xml elements. I have tested pojo classes without namespace and prefix its working fine .Though when i am trying to parse with namespaces and prefix facing the following exception.Requirement is to parse the input from SOAPMessage Object

javax.xml.bind.UnmarshalException:意外元素(uri:http://schemas.xmlsoap.org/soap/envelope/",本地:Envelope").预期元素为<{}Envelope>

尝试通过在 package-info.java 中为包创建 @XMLSchema 来修复并将此文件放在包文件夹中.有人能指导我继续吗?

Tried to fix by creating @XMLSchema for the package in package-info.java and located this file in package folder.Can any one guide me to move forward?

引用此帖子但对我没有帮助.

Referred this posts but didn help me .

已XMLSchema

@javax.xml.bind.annotation.XmlSchema (
    xmlns = {  @javax.xml.bind.annotation.XmlNs(prefix = "env", 
                 namespaceURI="http://schemas.xmlsoap.org/soap/envelope/"),
      @javax.xml.bind.annotation.XmlNs(prefix="ns3", namespaceURI="http://www.xxxx.com/ncp/oomr/dto/")
    }
  )
package com.one.two;

提前致谢

推荐答案

无需修改使用标准 SOAPMessage 类生成的 JAXB 代码即可完成此操作.我在这里这里

This can be done without modifying the generated JAXB code using standard SOAPMessage class. I wrote about this here and here

有点繁琐,但工作正常.

It's a little fiddly but works correctly.

Farm farm = new Farm();
farm.getHorse().add(new Horse());
farm.getHorse().get(0).setName("glue factory");
farm.getHorse().get(0).setHeight(BigInteger.valueOf(123));

Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Marshaller marshaller = JAXBContext.newInstance(Farm.class).createMarshaller();
marshaller.marshal(farm, document);
SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
soapMessage.getSOAPBody().addDocument(document);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
soapMessage.writeTo(outputStream);
String output = new String(outputStream.toByteArray());

解组

String example =
        "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header /><soapenv:Body><ns2:farm xmlns:ns2=\"http://adamish.com/example/farm\"><horse height=\"123\" name=\"glue factory\"/></ns2:farm></soapenv:Body></soapenv:Envelope>";
SOAPMessage message = MessageFactory.newInstance().createMessage(null,
        new ByteArrayInputStream(example.getBytes()));
Unmarshaller unmarshaller = JAXBContext.newInstance(Farm.class).createUnmarshaller();
Farm farm = (Farm)unmarshaller.unmarshal(message.getSOAPBody().extractContentAsDocument());

这篇关于JAXB 使用命名空间和前缀解组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆