如何删除 SOAPElement 中的前缀和命名空间?

问题描述 投票:0回答:2

同事们,我有一个循环,可以创建具有必要结构的soap xml(不要问结构)

log.info("Body elements: ");
NodeList nodeList = body.getElementsByTagName("*") ;
for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        log.info(node.getNodeName());

        if (node.getNodeName().equals("ns2:request")) {
            log.info("Set namespace and prefix for " + node.getNodeName());
            SOAPElement childX = (SOAPElement) node;
            childX.removeNamespaceDeclaration(childX.getPrefix()) ;
            childX.addNamespaceDeclaration("ns3", "http://mayacomp/Generic/Ws");
            childX.setPrefix("ns3");
        }

        else {                        
            if (node.getNodeName().equals("ns2:in") ) {
                log.info("Remove namespace for  " + node.getNodeName());
                SOAPElement childX = (SOAPElement) node;
                childX.removeNamespaceDeclaration(childX.getPrefix()) ;
                childX.addNamespaceDeclaration("", "");
                childX.setPrefix("");
            }

            SOAPElement childX = (SOAPElement) node;
            childX.removeNamespaceDeclaration(childX.getPrefix()) ;
            childX.setPrefix("");
        }
    }
}

结果我收到了 xml:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns3:request xmlns:ns3="http://mayacomp/Generic/Ws">
         <in xmlns="http://mayacomp/Generic/Ws">
            <requestHeader>

我的问题是如何从

xmlns="http://mayacomp/Generic/Ws"
元素中仅删除
<in>
并接收:

   <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
       <soapenv:Body>
          <ns3:request xmlns:ns3="http://mayacomp/Generic/Ws">
             <in>
                <requestHeader>

更新

我尝试配置 xml 元素:

    /*Config body elements*/
                while (itBodyElements.hasNext()) 
                {  
                  Object o = itBodyElements.next();
                  SOAPBodyElement bodyElement = (SOAPBodyElement) o;
                  log.info("Elements from 'Body' element = " + bodyElement.getLocalName() );

                  Iterator it2 = bodyElement.getChildElements();
                         while (it2.hasNext()) 
                         { 
                              Object requestElement = it2.next();
                              SOAPBodyElement bodyRequest = (SOAPBodyElement) requestElement;
                              log.info("  Elements from '"+ bodyElement.getLocalName() + "' element = " + bodyRequest.getLocalName()); 
                              log.info("  Delete namespace from IN element " + bodyRequest.getLocalName());
                              bodyRequest.removeNamespaceDeclaration(bodyRequest.getPrefix());
                              bodyRequest.setPrefix("");

                               Iterator it3 = bodyRequest.getChildElements();
                                    while (it3.hasNext())
                                    { //work with other elements

但对“in”元素没有影响。运行后我仍然有:

<in xmlns="http://mayacomp/Generic/Ws">

更新

我通过调用 ws 解决了问题:

getWebServiceTemplate().marshalSendAndReceive(
                "URL",
                request,
                new WebServiceMessageCallback()
                { public void doWithMessage(WebServiceMessage message) {

                        SaajSoapMessage saajSoapMessage = (SaajSoapMessage)message;

                        SOAPMessage soapMessage = UtilsClass.createSOAPMessage(in);

                        saajSoapMessage.setSaajMessage(soapMessage);

                }

                } 
                );

方法createSOAPMessage使用javax.xml.soap库配置soap消息。

java xml dom wsdl saaj
2个回答
0
投票

如果我正确理解了问题,您的代码将获取以下 XML 作为输入:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns2:request xmlns:ns3="http://mayacomp/Generic/Ws">
         <ns2:in>
            <ns2:requestHeader>

并且您想将其转换为以下 XML:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns3:request xmlns:ns3="http://mayacomp/Generic/Ws">
         <in>
            <requestHeader>

在这种情况下,调整命名空间声明和命名空间前缀是不够的,因为在 DOM 中,

in
requestHeader
元素仍位于
http://mayacomp/Generic/Ws
命名空间中。这是因为 DOM 元素的命名空间 URI 在创建/解析时确定,并且在稍后添加或删除命名空间声明时不会更改。当 DOM 被序列化时,序列化器将自动生成必要的命名空间声明,以确保输出中的元素有效地具有它们在 DOM 中的命名空间。这就是为什么你在输出中得到
xmlns="http://mayacomp/Generic/Ws"
,尽管 DOM 中不存在该命名空间声明。

您真正需要做的是更改这些元素的名称空间 URI。不幸的是,DOM 节点没有

setNamespaceURI
方法,您需要使用
Document.renameNode
来代替。


0
投票

您可以使用类似的方法删除该属性

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nList = (NodeList)xPath.evaluate("/Envelope/Body/request/in", body, XPathConstants.NODESET);
    for (int i = 0; i < nList.getLength(); ++i) {
        Element e = (Element) nList.item(i);
        e.removeAttribute("xmlns");
    }

以下测试表明它确实有效。

@Test
public void removeXmlns() throws Exception {
    String xml = "" +
            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
            "   <soapenv:Body>\n" +
            "      <ns3:request xmlns:ns3=\"http://mayacomp/Generic/Ws\">\n" +
            "         <in xmlns=\"http://mayacomp/Generic/Ws\">\n" +
            "            <requestHeader>\n" +
            "            </requestHeader>\n" +
            "         </in>\n" +
            "      </ns3:request>\n" +
            "   </soapenv:Body>\n" +
            "</soapenv:Envelope>";


    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = builder.parse(ResourceUtils.getFile("/soaptest.xml").getAbsolutePath());
    Element body = document.getDocumentElement();

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nList = (NodeList)xPath.evaluate("/Envelope/Body/request/in", body, XPathConstants.NODESET);
    for (int i = 0; i < nList.getLength(); ++i) {
        Element e = (Element) nList.item(i);
        e.removeAttribute("xmlns");
    }
    DOMSource domSource = new DOMSource(document);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
    logger.info("XML IN String format is: \n" + writer.toString());     
}

输出是

2015-11-26-11-46-24[]::[main]:(demo.TestCode.removeXmlns(TestCode.java:174):174):INFO :TestCode:XML IN String format is: 
<?xml version="1.0" encoding="UTF-8" standalone="no"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns3:request xmlns:ns3="http://dfg/Ws">
         <in>
            <requestHeader>
            </requestHeader>
         </in>
      </ns3:request>
   </soapenv:Body>
</soapenv:Envelope>
© www.soinside.com 2019 - 2024. All rights reserved.