微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从标记中删除命名空间但保留其前缀?

我能够生成SOAP消息,但我不知道

>只为soapMessage标记添加前缀(不应该有命名空间)

 SOAPConnectionFactory soapConnectionFactory =
                SOAPConnectionFactory.newInstance();
 SOAPConnection connection =
                soapConnectionFactory.createConnection();
 SOAPFactory soapFactory =
                SOAPFactory.newInstance();

 MessageFactory factory =
                MessageFactory.newInstance(SOAPConstants.soAP_1_2_PROTOCOL);

 SOAPMessage message = factory.createMessage();
 SOAPHeader header = message.getSOAPHeader();
 SOAPPart soapPart = message.getSOAPPart();
 SOAPEnvelope soapEnvelope = soapPart.getEnvelope();                
 SOAPBody body = soapEnvelope.getBody();

 soapEnvelope.removeNamespaceDeclaration(soapEnvelope.getPrefix());
 soapEnvelope.setPrefix("soap");
 body.setPrefix("soap");

 header.removeNamespaceDeclaration(header.getPrefix());
 header.setPrefix("soap");

 soapEnvelope.addNamespaceDeclaration("v9", "URL TO SERVER");

 Name bodyName;
 bodyName = soapFactory.createName("SearchHotels");
 SOAPBodyElement getList = body.addBodyElement(bodyName);
 getList.setPrefix("v9");

 Name childName = soapFactory.createName("SoapMessage", "v9", "URL TO SERVER");
 SOAPElement HotelListRequest = getList.addChildElement(childName);

 HotelListRequest.addChildElement("Hotel", "v9").addTextNode("Hilton");

我的SOAP消息

   ...
     <v9:SoapMessage xmlns:els="URL TO SERVER">
         ...

我所期待的

   ...
      <v9:SoapMessage>
           ...

更新:

如果我使用以下内容,则会遇到以下错误

    SOAPElement HotelListRequest = getList.addChildElement("v9:SoapMessage");

    org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a 
                                             way which is incorrect with regard to namespaces.

解决方法:

要为所有标记添加名称空间前缀,您必须在每个插入的子项上重新声明所需的前缀(最终是名称空间),否则它将从父元素继承(隐含地)名称空间.

试试例如:

SOAPBodyElement getList = body.addBodyElement(bodyName, "v9", "http://URL TO SERVER");

要么

soapBody.addChildElement("SomeElement", "v9", "http://URL TO SERVER");

要么

soapBody.addChildElement("v9:SomeElement");

有时您可能必须使用QName对象而不仅仅是String或Name.

它几乎取决于您使用的SOAP-API / Implementation,但原则在任何地方都是相同的:重新声明(显式)或继承(隐式).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。