JAXB解组使用名称空间和前缀 [英] JAXB unmarshall with namespaces and prefix
问题描述
我正在使用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:unexpected element(uri:http://schemas.xmlsoap.org/soap/envelope/,local: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 此帖子但没有帮助我。
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());
Unmarshalling
Unmarshalling
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屋!