java - 如何从标签中删除 namespace 但保留其前缀?

标签 java xml web-services jakarta-ee soap

我能够生成 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.

最佳答案

要将 namespace 前缀添加到所有标签,您必须在每个 插入的子元素上重新声明所需的前缀(最终是 namespace ),否则它将(隐式地)从父元素继承 namespace .

例如尝试:

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

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

soapBody.addChildElement("v9:SomeElement");

有时您可能不得不使用 QName 对象,而不仅仅是 StringName

这在很大程度上取决于您使用的 SOAP-API/实现,但原则在任何地方都是相同的:重新声明(显式)或继承(隐式)。

关于java - 如何从标签中删除 namespace 但保留其前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19763977/

相关文章:

java - 从家庭 Activity 将变量值传递给类(不是 Intent )

java - 如何使@Documented注释保留泛型信息?

xml - 如何在解码 xml 时忽略命名空间

java - 为什么 Tomcat 会报 403 错误?

java - 无法为 JSP : BooksWorker cannot be resolved 编译类

java - 需要在此表上添加表头

java - 从 PHP 调用 Web 服务

java - 在 Spring Rest 模板中设置超时

c# - XDocument 不会解析 html 实体(例如 ),但 XmlDocument 会

javascript - 删除生成的字段 javascript