使用命名空间和前缀进行 JAXB 解组

2024-04-25

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

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Envelope"). Expected elements are <{}Envelope>

尝试通过在 package-info.java 中为包创建 @XMLSchema 并将该文件放在包文件夹中来修复。任何人都可以指导我继续前进吗?

Referred https://stackoverflow.com/questions/17483699/unmarshaling-of-soap-response-with-namespace-prefix这篇文章但对我没有帮助。

编辑: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 代码即可完成此操作。我写过这个here http://adamish.com/blog/archives/707 and here http://adamish.com/blog/archives/711

它有点繁琐,但工作正常。

编组

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());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用命名空间和前缀进行 JAXB 解组 的相关文章

随机推荐