Example usage for org.w3c.dom Element getParentNode

List of usage examples for org.w3c.dom Element getParentNode

Introduction

In this page you can find the example usage for org.w3c.dom Element getParentNode.

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:fr.aliasource.webmail.common.cache.ConversationCache.java

/**
 * Finds the conversation id of a message id
 *//* w  w  w . j a v a  2  s.c  om*/
public String findConversationId(IFolder f, MessageId mid) {
    Document refs = cache(f).getDOM();

    String ret = null;
    String toFind = "" + mid.getImapId();
    if (refs != null) {
        NodeList mids = refs.getElementsByTagName("mid");
        int len = mids.getLength();
        Element foundMid = null;
        for (int i = 0; i < len; i++) {
            Element mide = (Element) mids.item(i);
            if (toFind.equals(mide.getAttribute("id"))) {
                foundMid = mide;
                break;
            }
        }
        if (foundMid != null) {
            Element conv = (Element) foundMid.getParentNode().getParentNode();
            ret = conv.getAttribute("id");
        }
    } else {
        logger.warn("No ref cache for " + f.getName());
    }
    if (logger.isDebugEnabled()) {
        logger.debug("findConversationId(" + f.getName() + ", " + mid.getImapId() + ") => " + ret);
    }
    return ret;
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

private static String findNamespaceForPrefix(Element elm, String prefix) {
    String namespaceUri = null;/* ww  w.  ja  v  a 2 s  .  co m*/
    while (StringUtils.isBlank(namespaceUri) && elm != null) {
        if (elm.getParentNode().getNodeType() != Node.ELEMENT_NODE)
            break;

        elm = (Element) elm.getParentNode();
        namespaceUri = elm.getAttribute("xmlns:" + prefix);
    }

    return StringUtils.isBlank(namespaceUri) ? null : namespaceUri;
}

From source file:fi.csc.emrex.smp.ThymeController.java

@RequestMapping(value = "/onReturn", method = RequestMethod.POST)
public String onReturnelmo(@ModelAttribute ElmoData request, Model model,
        @CookieValue(value = "elmoSessionId") String sessionIdCookie,
        @CookieValue(value = "chosenNCP") String chosenNCP,
        //@CookieValue(value = "chosenCert") String chosenCert,
        HttpServletRequest httpRequest) throws Exception {
    String sessionId = request.getSessionId();
    String elmo = request.getElmo();

    Person person = (Person) context.getSession().getAttribute("shibPerson");

    if (person == null) {
        ShibbolethHeaderHandler headerHandler = new ShibbolethHeaderHandler(httpRequest);
        log.debug(headerHandler.stringifyHeader());
        person = headerHandler.generatePerson();
        context.getSession().setAttribute("shibPerson", person);
    }/*  w  w w.  ja va 2  s  . c o  m*/

    String source = "SMP";
    String personalLogLine = generatePersonalLogLine(httpRequest, person, source);
    log.info(request.getReturnCode());
    if (!"NCP_OK".equalsIgnoreCase(request.getReturnCode())) {
        log.error("NCP not OK");
        if ("NCP_NO_RESULTS".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "No courses found on NCP.");
            log.error("No courses found on NCP.");
        }
        if ("NCP_CANCEL".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "User cancelled transfer on NCP.");
            log.error("User cancelled transfer on NCP.");
        }
        if ("NCP_ERROR".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "Error on NCP.");
            log.error("Error on NCP.");
        }
        return abort(model);
    }
    log.info("NCP OK!");
    if (elmo == null || elmo.isEmpty()) {
        PersonalLogger.log(personalLogLine + "\tfailed");
        log.error("ELMO-xml empy or null.");
        return abort(model);
    }
    String ncpPubKey = this.getCertificate(chosenNCP);
    final String decodedXml;
    final boolean verifySignatureResult;
    try {
        final byte[] bytes = DatatypeConverter.parseBase64Binary(elmo);
        decodedXml = GzipUtil.gzipDecompress(bytes);
        verifySignatureResult = signatureVerifier.verifySignatureWithDecodedData(ncpPubKey, decodedXml,
                StandardCharsets.UTF_8);

        log.info("Verify signature result: {}", verifySignatureResult);
        log.info("providedSessionId: {}", sessionId);

        FiSmpApplication.verifySessionId(sessionId, sessionIdCookie);
    } catch (Exception e) {
        log.error("Session verification failed", e);
        model.addAttribute("error", "Session verification failed");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    try {
        if (!verifySignatureResult) {
            log.error("NCP signature check failed");
            model.addAttribute("error", "NCP signature check failed");
            PersonalLogger.log(personalLogLine + "\tfailed");
            return "error";
        }
    } catch (Exception e) {
        log.error("NCP verification failed", e);
        model.addAttribute("error", "NCP verification failed");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }

    log.info("Returned elmo XML " + decodedXml);
    context.getSession().setAttribute("elmoxmlstring", decodedXml);
    ElmoParser parser = ElmoParser.elmoParser(decodedXml);
    try {
        byte[] pdf = parser.getAttachedPDF();
        context.getSession().setAttribute("pdf", pdf);
    } catch (Exception e) {
        log.error("EMREX transcript missing.");
        model.addAttribute("error", "EMREX transcript missing.");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    model.addAttribute("elmoXml", decodedXml);

    Document document;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //Get the DOM Builder
    DocumentBuilder builder;
    if (person != null) {
        List<VerifiedReport> results = new ArrayList<>();
        try {

            builder = factory.newDocumentBuilder();
            StringReader sr = new StringReader(decodedXml);
            final InputSource inputSource = new InputSource();
            inputSource.setEncoding(StandardCharsets.UTF_8.name());
            inputSource.setCharacterStream(sr);
            //person.setFirstName("test"); person.setLastName("user");
            //person.setHomeOrganizationName("test institution");
            //Load and Parse the XML document
            //document contains the complete XML as a Tree.
            document = builder.parse(inputSource);
            NodeList reports = document.getElementsByTagName("report");
            for (int i = 0; i < reports.getLength(); i++) {
                VerifiedReport vr = new VerifiedReport();
                Element report = (Element) reports.item(i);
                vr.setReport(nodeToString(report));
                Person elmoPerson = getUserFromElmoReport((Element) report.getParentNode());

                if (elmoPerson != null) {
                    VerificationReply verification = VerificationReply.verify(person, elmoPerson,
                            verificationThreshold);
                    log.info("Verification messages: " + verification.getMessages());
                    log.info("VerScore: " + verification.getScore());

                    vr.setVerification(verification);

                } else {
                    vr.addMessage("Elmo learner missing");
                    //TODO fix this
                }
                results.add(vr);
            }
            context.getSession().setAttribute("reports", results);
            model.addAttribute("reports", results);

        } catch (ParserConfigurationException | IOException | SAXException ex) {
            log.error("Error in report verification", ex);
            model.addAttribute("error", ex.getMessage());
            PersonalLogger.log(personalLogLine + "\tfailed");
            return "error";
        }
    } else {
        model.addAttribute("error", "HAKA login missing");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    PersonalLogger.log(personalLogLine + "\tokay");
    return "review";
}

From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfParser.java

/**
 * Produces several descriptions based on the different hardware configuration defined in the OVF
 * descriptor.//from   w w w.j a v a  2 s  .  c o  m
 * @param doc OVF descriptor to parse
 * @param template use as a basis of the ComputeDescription.
 * @return
 */
public List<ComputeDescription> parse(Document doc, ComputeDescription template) {
    NodeList networks = nodes(doc, "/ovf:Envelope/ovf:NetworkSection/ovf:Network");

    CustomProperties cust = CustomProperties.of(template);

    for (Element network : iterableElements(networks)) {
        cust.put(network(attr("ovf:name", network)), text(network, "ovf:Description/text()"));
    }

    NodeList props = nodes(doc, "/ovf:Envelope/ovf:VirtualSystem/ovf:ProductSection/ovf:Property");
    for (Element prop : iterableElements(props)) {
        String userConfigurable = attr("ovf:userConfigurable", prop);
        if (!"true".equals(userConfigurable)) {
            continue;
        }
        String key = attr("ovf:key", prop);
        Element section = (Element) prop.getParentNode();
        String instanceId = attr("ovf:instance", section);
        String classId = attr("ovf:class", section);
        String description = text(prop, "ovf:Description/text()");

        cust.put(property(classId, key, instanceId), description);
    }

    String productName = text(doc, "/ovf:Envelope/ovf:VirtualSystem/ovf:ProductSection/ovf:Product/text()");
    String productVersion = text(doc, "/ovf:Envelope/ovf:VirtualSystem/ovf:ProductSection/ovf:Version/text()");
    template.name = productName + " " + productVersion;

    NodeList hwItems = nodes(doc, "/ovf:Envelope/ovf:VirtualSystem/ovf:VirtualHardwareSection/ovf:Item");

    Map<String, ComputeDescription> hwByConfigName = new HashMap<>();

    for (Element item : iterableElements(hwItems)) {
        String configName = attr("ovf:configuration", item);
        ComputeDescription desc = hwByConfigName.get(configName);
        if (desc == null) {
            desc = Utils.clone(template);
            desc.documentSelfLink = UUID.randomUUID().toString();
            desc.id = "ovf-imported-" + desc.documentSelfLink;
            desc.customProperties.put(PROP_OVF_CONFIGURATION, configName);
            hwByConfigName.put(configName, desc);
        }

        String resourceType = text(item, "rasd:ResourceType/text()");
        if (RESOURCE_TYPE_CPU.equals(resourceType)) {
            long qty = Long.parseLong(text(item, "rasd:VirtualQuantity/text()"));
            desc.cpuCount = qty;
        }

        if (RESOURCE_TYPE_MEMORY.equals(resourceType)) {
            double qty = Double.parseDouble(text(item, "rasd:VirtualQuantity/text()"));
            long mult = memAllocationUnit2Multiplier(text(item, "rasd:AllocationUnits/text()"));
            desc.totalMemoryBytes = (long) (qty * mult);
        }
    }

    for (Iterator<ComputeDescription> it = hwByConfigName.values().iterator(); it.hasNext();) {
        ComputeDescription desc = it.next();
        if (desc.cpuCount <= 0) {
            it.remove();
        }
    }

    return new ArrayList<>(hwByConfigName.values());
}

From source file:com.wfreitas.camelsoap.SoapClient.java

/**
 * Clone a collection node./*from   w  ww.j  ava2  s  .  co  m*/
 * <p/>
 * Note we have to frig with the OGNL expressions for collections/arrays because the
 * collection entry is represented by [0], [1] etc in the OGNL expression, not the actual
 * element name on the DOM e.g. collection node "order/items/item" (where "item" is the
 * actual collection entry) maps to the OGNL expression "order.items[0]" etc.
 *
 * @param element    The collection/array "entry" sub-branch.
 * @param cloneCount The number of times it needs to be cloned.
 * @param ognl       The OGNL expression for the collection/array. Not including the
 *                   indexing part.
 */
private void cloneCollectionTemplateElement(Element element, int cloneCount, String ognl) {
    if (element == null) {
        return;
    }

    Node insertPoint = element.getNextSibling();
    Node parent = element.getParentNode();

    element.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS,
            OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + OGNLUtils.OGNL_ATTRIB, ognl + "[0]");
    for (int i = 0; i < cloneCount; i++) {
        Element clone = (Element) element.cloneNode(true);

        clone.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS, OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + IS_CLONE_ATTRIB,
                "true");
        clone.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS,
                OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + OGNLUtils.OGNL_ATTRIB,
                ognl + "[" + Integer.toString(i + 1) + "]");
        if (insertPoint == null) {
            parent.appendChild(clone);
        } else {
            parent.insertBefore(clone, insertPoint);
        }
    }
}

From source file:kml.feature.Placemark.java

public void setPlacemarkElement(Element element) {
    try {// ww  w  .ja v  a 2  s  .  c o  m
        this.setParent(element.getParentNode().getNodeName());
    } catch (Exception ex) {
        this.setParent("UNKNOWN");
    }

    // id attribute
    if (element.getAttribute("id").length() > 0) {
        String id = element.getAttribute("id");
        this.setId(id);
    } // id
      // name element
    if (element.getElementsByTagNameNS("*", "name").getLength() > 0) {
        String name = element.getElementsByTagNameNS("*", "name").item(0).getTextContent();
        this.setName(name);
    } // name
    if (element.getElementsByTagNameNS("*", "description").getLength() > 0) {
        String description = element.getElementsByTagNameNS("*", "description").item(0).getTextContent();
        this.setDescription(description);
    } // description     
    if (element.getElementsByTagNameNS("*", "Style").getLength() > 0) {
        this.style.setStyleElement(element);
    } // Style   
    if (element.getElementsByTagNameNS("*", "StyleMap").getLength() > 0) {
        this.styleMap.setElement(element);
    } // StyleMap        
    int suKnt = element.getElementsByTagNameNS("*", "styleUrl").getLength();
    if (element.getElementsByTagNameNS("*", "styleUrl").getLength() > 0) {
        //String styleUrl = element.getElementsByTagNameNS("*","styleUrl").item(0).getTextContent();
        //pm.append("styleUrl: ").append(styleUrl).append("\n");
        for (int knt = 0; knt < suKnt; knt++) {
            String styleUrl = element.getElementsByTagNameNS("*", "styleUrl").item(knt).getTextContent();
            this.setStyleUrl(styleUrl);
        }
        //System.out.println("element styleUrl : " + element.getElementsByTagNameNS("*","styleUrl").item(0).getTextContent());
    } // styleUrl    

    // IGNORE MultiGeometry because the child elements are geometris that are parsed anyway
    //                if (element.getElementsByTagNameNS("*","MultiGeometry").getLength() > 0) {
    //                    //TODO
    //                }// MultiGeometry    
    int polyKnt = element.getElementsByTagNameNS("*", "Polygon").getLength();
    if (polyKnt > 0) {
        NodeList polyNodes = element.getElementsByTagNameNS("*", "Polygon"); //NodeList
        if (polyNodes != null) {
            for (int i = 0; i < polyNodes.getLength(); i++) {
                if (polyNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    Element polyElement = (Element) polyNodes.item(i);
                    Polygon polygon = new Polygon(polyElement);
                    //System.out.println("Adding Polygon[" + i + "] id:" + polygon.getId());
                    this.addGeometry(polygon.getId(), polygon);
                }
            }
        }
        //            for (int knt = 0; knt < polyKnt; knt++) {
        //                Element polyElement = (Element) element.getElementsByTagNameNS("*","Polygon").item(knt);
        //                Polygon polygon = new Polygon(polyElement);
        //                System.out.println("Adding Polygon[" + knt + "] id:" + polygon.getId() + " " + polygon.toString());
        //                this.addGeometry(polygon.getId(), polygon);
        //
        //            }
    } // Polygon ====================================================
      //System.out.println("      Placemark.setPlacemarkElement element.getTagName() " + element.getTagName());
    if (element.getTagName().equals("Polygon")) {
        Polygon polygon = new Polygon(element);
        System.out.println("Adding Polygon[ORPHAN] id:" + polygon.getId());
        this.addGeometry(polygon.getId(), polygon);
    } // Polygon Orphan ====================================================
    int pointKnt = element.getElementsByTagNameNS("*", "Point").getLength();
    if (pointKnt > 0) {
        for (int knt = 0; knt < pointKnt; knt++) {
            Point point = new Point(element);
            //System.out.println("Adding LineString[" + knt + "] id:" + lineString.getId() + "\n" + lineString.getCoordinates());
            this.addGeometry(point.getId(), point);
        }
    } // Point ====================================================== 
    if (element.getTagName().equals("Point")) {
        Point point = new Point(element);
        System.out.println("Adding Point[ORPHAN] id:" + point.getId());
        this.addGeometry(point.getId(), point);
    } // Point Orphan ====================================================        
    int lsKnt = element.getElementsByTagNameNS("*", "LineString").getLength();
    if (lsKnt > 0) {
        for (int knt = 0; knt < lsKnt; knt++) {
            LineString lineString = new LineString(element);
            //System.out.println("Adding LineString[" + knt + "] id:" + lineString.getId() + "\n" + lineString.getCoordinates());
            this.addGeometry(lineString.getId(), lineString);
        }
    } // LineString =================================================
    //            if (lsKnt > 0) {
    //                NodeList lsNodes = element.getElementsByTagNameNS("*","LineString"); //NodeList
    //                if (lsNodes != null) {
    //                    for (int knt = 0; knt < lsKnt; knt++) {
    //                        if (lsNodes.item(knt).getNodeType() == Node.ELEMENT_NODE) {
    //                            LineString lineString = new LineString((Element) lsNodes.item(knt));
    //                            //System.out.println("Adding LineString[" + knt + "] id:" + lineString.getId() + "\n" + lineString.getCoordinates());
    //                            this.addGeometry(lineString.getId(), lineString);
    //                        }
    //                    }
    //                }
    //            }        
    if (element.getTagName().equals("LineString")) {
        LineString lineString = new LineString(element);
        System.out.println("Adding LineString[ORPHAN] id:" + lineString.getId());
        this.addGeometry(lineString.getId(), lineString);
    } // LineString Orphan ====================================================         
      // Is this necessary since it is part of a Polygon?
      //                int lrKnt = element.getElementsByTagNameNS("*","LinearRing").getLength();
      //                if (element.getElementsByTagNameNS("*","LinearRing").getLength() > 0) {
      //                    for (int knt = 0; knt < lrKnt; knt++) {
      //                        System.out.println("Adding LinearRing[" + knt + "] ");
      //                        LinearRing linearRing = new LinearRing(element);
      //                        this.addGeometry(linearRing.getId(), linearRing);
      //                    }
      //                }// LinearRing ================================================= 
}

From source file:org.gvnix.dynamic.configuration.roo.addon.ConfigurationsImpl.java

/**
 * {@inheritDoc}/*from   w  w w  .jav a2s . c o  m*/
 */
public void deleteConfiguration(Element conf) {

    // Remove configuration element and their child component elements
    List<Element> comps = XmlUtils.findElements(COMPONENT_ELEMENT_NAME, conf);
    for (Element comp : comps) {
        conf.removeChild(comp);
    }
    conf.getParentNode().removeChild(conf);

    // If active configuration, remove the reference on configuration file
    Element activeConf = isActiveConfiguration(conf);
    if (activeConf != null) {
        activeConf.setTextContent("");
    }

    // Update the configuration file
    saveConfiguration(conf);
}

From source file:org.apache.flex.utilities.converter.retrievers.download.DownloadRetriever.java

public Map<DefaultArtifactVersion, Collection<PlatformType>> getAvailableVersions(SdkType type) {
    Map<DefaultArtifactVersion, Collection<PlatformType>> result = new HashMap<DefaultArtifactVersion, Collection<PlatformType>>();
    try {//from   w  ww . j a va 2s.com
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.parse(getFlexInstallerConfigUrl());
        final XPath xPath = XPathFactory.newInstance().newXPath();

        String expression;
        NodeList nodes = null;
        switch (type) {
        case FLEX:
            expression = "/config/products/ApacheFlexSDK/versions/*";
            nodes = (NodeList) xPath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            break;
        case FLASH:
            expression = "/config/flashsdk/versions/*";
            nodes = (NodeList) xPath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            break;
        case AIR:
            expression = "/config/airsdk/*/versions/*";
            nodes = (NodeList) xPath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            break;
        }

        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                Element element = (Element) nodes.item(i);
                DefaultArtifactVersion version = new DefaultArtifactVersion(element.getAttribute("version"));
                if (type == SdkType.AIR) {
                    PlatformType platformType = PlatformType
                            .valueOf(element.getParentNode().getParentNode().getNodeName().toUpperCase());
                    if (!result.containsKey(version)) {
                        result.put(version, new ArrayList<PlatformType>());
                    }
                    result.get(version).add(platformType);
                } else {
                    result.put(version, null);
                }
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:de.betterform.xml.xforms.ui.AbstractUIElement.java

protected String getTargetReference(Element node, String targetRef) {

    if (node == null)
        return targetRef;
    if (!(node instanceof Element))
        return targetRef;

    Object xfObject = ((Element) node).getUserData("");
    if (xfObject != null && xfObject instanceof RepeatItem) {
        int position = ((RepeatItem) xfObject).getPosition();
        targetRef = "," + position + "]/" + targetRef;

    } else if (xfObject != null && xfObject instanceof Repeat) {
        int position = ((Repeat) xfObject).getPosition();
        targetRef = "[" + position + "" + targetRef;

    }//from ww w .j  av  a2 s.  c  om
    Node parent = node.getParentNode();
    if (parent.getNodeType() == Node.DOCUMENT_NODE || parent.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE
            || parent == null) {
        return "/" + targetRef;
    } else if (parent.getNodeType() == Node.ELEMENT_NODE) {
        return getTargetReference((Element) parent, targetRef);
    } else {
        LOGGER.warn("Unkown type: " + parent);
        return targetRef;
    }
}

From source file:com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction.java

@Override
public void makeDocument(byte[] httpData) throws Exception {
    Engine.logBeans.trace("makeDocument : " + getEncodingCharSet());

    Charset charset = XMLUtils.getEncoding(httpData, Charset.forName(xmlEncoding));

    String sdata = new String(httpData, charset);
    sdata = sdata.replaceFirst("[\\d\\D]*?<", "<");
    Engine.logBeans.trace("makeDocument afternewString: " + sdata);

    Document xmlHttpDocument = requester.parseDOM(sdata);
    if (Engine.logBeans.isTraceEnabled())
        Engine.logBeans.trace("makeDocument after parseDom: " + XMLUtils.prettyPrintDOM(xmlHttpDocument));

    // Replace SOAP fault by an c8o error element
    if (isErrorOnSoapFault()) {
        Element soapFaultElement = null;
        soapFaultElement = getSoapFaultElement(xmlHttpDocument);
        if (soapFaultElement != null) {
            String sfm = getSoapFaultMessage(soapFaultElement);
            ConvertigoException ex = new ConvertigoException("The Web Service returned a SOAP Fault",
                    new SOAPException(sfm));
            ConvertigoError err = ConvertigoError.initError(ErrorType.Project, ex);
            Document errDocument = err.buildErrorDocument(getRequester(), context);
            Node error = context.outputDocument.importNode(errDocument.getDocumentElement().getFirstChild(),
                    true);/*from   w w  w.j  av a  2 s . c o  m*/
            context.outputDocument.getDocumentElement().appendChild(error);
            return;
        }
    }

    if (getAllowDownloadAttachment()) {
        Element attachmentInfo = (Element) XPathAPI.selectSingleNode(context.outputDocument,
                "/document/AttachmentInfo");

        if (attachmentInfo != null) {
            NodeList nl = XPathAPI.selectNodeList(attachmentInfo, "attachment");

            for (int i = 0; i < nl.getLength(); i++) {
                Element attachment = (Element) nl.item(i);
                String cid = attachment.getAttribute("cid");

                if (StringUtils.isNotBlank(cid)) {
                    Element include = (Element) XPathAPI.selectSingleNode(xmlHttpDocument,
                            "//*[local-name()='Include' and @href='" + cid + "']");

                    if (include != null) {
                        include.appendChild(xmlHttpDocument.importNode(attachment, true));
                        XMLUtils.removeNode(attachment);
                    }
                }
            }

            if (XPathAPI.selectSingleNode(attachmentInfo, "attachment") == null) {
                XMLUtils.removeNode(attachmentInfo);
            }
        }
    }

    // Removes soap elements if needed
    if (isIgnoreSoapEnveloppe()) {
        Element soapBodyResponseElement = null;
        soapBodyResponseElement = getSoapBodyResponseElement(xmlHttpDocument.getDocumentElement());
        if (soapBodyResponseElement != null) {
            NamedNodeMap attributes = ((Element) soapBodyResponseElement.getParentNode()).getAttributes();
            NodeList childNodes = soapBodyResponseElement.getChildNodes();
            int len = childNodes.getLength();
            Node child, node;
            for (int i = 0; i < len; i++) {
                node = childNodes.item(i);
                if (node instanceof Element) {
                    //child = importNodeWithNoPrefix(context.outputDocument, node, true);
                    child = context.outputDocument.importNode(node, true);
                    // add envelope attributes (e.g namespace declarations to avoid unbound prefixes for XSL transformation)
                    for (int j = 0; j < attributes.getLength(); j++) {
                        Node attr = attributes.item(j);
                        ((Element) child)
                                .setAttributeNode((Attr) context.outputDocument.importNode(attr, true));
                    }
                    context.outputDocument.getDocumentElement().appendChild(child);
                }
            }
        } else {
            XMLUtils.copyDocument(xmlHttpDocument, context.outputDocument);
        }
    }
    // Normal case
    else
        XMLUtils.copyDocument(xmlHttpDocument, context.outputDocument);
}