Example usage for org.w3c.dom Element removeChild

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

Introduction

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

Prototype

public Node removeChild(Node oldChild) throws DOMException;

Source Link

Document

Removes the child node indicated by oldChild from the list of children, and returns it.

Usage

From source file:com.sap.research.roo.addon.nwcloud.NWCloudOperationsImpl.java

/**
 * Remove the passed "plugin" from the containing element defined by "containingPath"
 * in the path of "path". This function is called by removeBuildPlugin(Plugin plugin),
 * which is a convenience function to call this function for the use case of removing
 * build plugins from the "pom.xml" file.
 * /*  w  ww  . j a va  2  s  .  c om*/
 * @param plugin org.springframework.roo.project.Plugin to remove from "pom.xml"
 * @param containingPath String of path to containing element to remove plugin from
 * @param path String of path to remove the plugin from
 */
private void removeBuildPlugin(Plugin plugin, String containingPath, String path) {

    if (plugin != null) {

        // Read "pom.xml" and store reference to root Element
        Document document = XmlUtils.readXml(fileManager.getInputStream(this.getPOM().getPath()));
        Element root = document.getDocumentElement();

        // Loop through all elements in the path of the containing element that match the
        // desired path of removal candidates. If the candidate matches the plugin that
        // should be removed, it will be removed from the "pom.xml".
        String descriptionOfChange = "";
        Element pluginsElement = XmlUtils.findFirstElement(containingPath, root);
        String pluginID = plugin.getGroupId() + plugin.getArtifactId();
        for (Element candidate : XmlUtils.findElements(path, root)) {
            try {
                Plugin candidatePlugin = new Plugin(candidate);
                String candidatePluginID = candidatePlugin.getGroupId() + candidatePlugin.getArtifactId();
                //log.log(Level.INFO, " - Comparing '"+pluginID+"' with '"+candidatePluginID+"'");
                if (pluginID.equals(candidatePluginID)) {
                    pluginsElement.removeChild(candidate);
                    descriptionOfChange = "Removal of build plugin: " + plugin.getArtifactId();
                    // We will not break the loop (even though we could theoretically), just in case it was declared in the POM more than once
                }
            } catch (Exception e) {
                // Ignore
            }
        }

        // Clean up the element containing the build plugins in "pom.xml"
        DomUtils.removeTextNodes(pluginsElement);

        // Update "pom.xml" file
        fileManager.createOrUpdateTextFileIfRequired(this.getPOM().getPath(), XmlUtils.nodeToString(document),
                descriptionOfChange, true);

    } else {
        this.log.warning(
                "NWCloud-AddOn: The given plugin object that should be removed from POM build plugins was null.");
    }

}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void removeEmtpyFields(Document doc) {
    Element root = (Element) doc.getElementsByTagName("Opus_Document").item(0);
    NodeList childNodes = root.getChildNodes();

    // removing nodes from the node list changes the node list
    // so for iteration is not invariant.
    ArrayList<Node> removees = new ArrayList<>(childNodes.getLength());

    for (int i = 0; i < childNodes.getLength(); i++) {
        Node childNode = childNodes.item(i);
        if (!childNode.hasChildNodes())
            removees.add(childNode);//from  w  w w.ja  v a 2  s  .  co  m
    }
    for (Node n : removees)
        root.removeChild(n);

}

From source file:Main.java

/**
 * If there is no <profiles> section, create one with relevant profile with given profileId
 * If <profiles> already contains a <profile> with given profileId, delete all of its plugins
 * @param document/*from   www . ja  v a  2  s.c om*/
 * @param pomRoot
 * @param profileIdVal
 * @return the <plugins> node (under profiles/profile/build), or null for any error
 */
public static Element initiateProfile(Document document, Element pomRoot, String profileIdVal) {
    //If <profiles> section does not exist, then create and get out
    NodeList childrenRoot = pomRoot.getChildNodes();
    int numProfileNodes = childrenRoot.getLength();
    Node profiles = null;
    for (int index = 0; index < numProfileNodes; index++) {
        Node currNode = childrenRoot.item(index);
        if (currNode.getNodeName().equals(PROFILES_NODE_NAME)) {
            profiles = currNode;
            break;
        }
    }
    if (profiles == null) {
        //no <profiles> section was found.
        //create <profiles>
        Element profilesNew = addProfilesSection(document, pomRoot);

        //Create <profile>, add to <profiles>, and get out
        return addNewProfileSection(document, profilesNew, profileIdVal);
    }

    //the <profiles> section already exists, go over all profiles to determine if the specific profile (with given profileIdVal) exists
    NodeList profileNodes = profiles.getChildNodes();
    numProfileNodes = profileNodes.getLength();
    boolean isProblem = false;
    Element profile = null;
    Element plugins = null;
    for (int profileIndex = 0; profileIndex < numProfileNodes; profileIndex++) {
        //Convert to Element if possible, otherwise it is not relevant
        Node profileNode = profileNodes.item(profileIndex);
        if (!(profileNode instanceof Element)) {
            continue;
        }
        Element currProfile = (Element) profileNode;

        NodeList profileChildren = currProfile.getChildNodes();
        int numProfileChildren = profileChildren.getLength();
        Element profileId = null;
        for (int indexProfileChildren = 0; indexProfileChildren < numProfileChildren; indexProfileChildren++) {
            if (!(profileChildren.item(indexProfileChildren) instanceof Element)) {
                continue;
            }

            if (profileChildren.item(indexProfileChildren).getNodeName().equals(PROFILE_ID_NAME)) {
                profileId = (Element) profileChildren.item(indexProfileChildren);
                break;
            }
        }
        if (profileId == null) {
            //we have a profile without an id, ignore it and move to the next one
            continue;
        }

        //Check if its id is the one we are interested in
        String currProfileIdVal = profileId.getTextContent();
        if (currProfileIdVal.equals(profileIdVal)) {
            profile = currProfile;
            //A profile was found with id = profileId
            //get/create the <build> element
            Element build = getChildElement(document, currProfile, BUILD_NAME);
            if (build == null) {
                isProblem = true;
                break;
            }

            //get/create the <plugins> element
            plugins = getChildElement(document, build, PLUGINS_NAME);
            if (plugins == null) {
                isProblem = true;
                break;
            }

            //remove all children from the <plugins> element (whether or not they are <plugin>'s)
            NodeList pluginNodes = plugins.getChildNodes();
            int numPluginsChildren = pluginNodes.getLength();
            for (int pluginIndex = numPluginsChildren - 1; pluginIndex >= 0; pluginIndex--) {
                plugins.removeChild(pluginNodes.item(pluginIndex));
            }

            //whatever happened above, we are done now, don't check any other profiles
            break;
        }
        //else continue to the next profile
    }

    if (isProblem)
        return null;

    if (profile == null) {
        //the required profile was never found.  Create it now, add to profiles, and get out
        return addNewProfileSection(document, (Element) profiles, profileIdVal);
    } else {
        //we did find the profile, so return the plugins element
        return plugins;
    }
}

From source file:com.mirth.connect.model.util.ImportConverter.java

private static void updateFilterFor2_0(Document document) {
    // Convert Rule Builder steps using "Reject" to JavaScript steps
    NodeList rules = getElements(document, "rule", "com.mirth.connect.model.Rule");

    for (int i = 0; i < rules.getLength(); i++) {
        Element rule = (Element) rules.item(i);

        if (rule.getElementsByTagName("type").item(0).getTextContent().equalsIgnoreCase("Rule Builder")) {
            boolean reject = false;
            NodeList entries = rule.getElementsByTagName("entry");
            for (int j = 0; j < entries.getLength(); j++) {
                NodeList entry = ((Element) entries.item(j)).getElementsByTagName("string");

                if ((entry.getLength() == 2) && entry.item(0).getTextContent().equalsIgnoreCase("Accept")
                        && entry.item(1).getTextContent().equalsIgnoreCase("0")) {
                    reject = true;/*from ww w  . ja v a2  s.com*/
                }
            }

            if (reject) {
                rule.getElementsByTagName("type").item(0).setTextContent("JavaScript");
                rule.removeChild(rule.getElementsByTagName("data").item(0));

                Element dataElement = document.createElement("data");
                dataElement.setAttribute("class", "map");

                Element entryElement = document.createElement("entry");
                Element keyElement = document.createElement("string");
                Element valueElement = document.createElement("string");

                keyElement.setTextContent("Script");
                valueElement.setTextContent(rule.getElementsByTagName("script").item(0).getTextContent());

                entryElement.appendChild(keyElement);
                entryElement.appendChild(valueElement);

                dataElement.appendChild(entryElement);

                rule.appendChild(dataElement);
            }
        }
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * /*from w  w  w.ja  v a2s. co m*/
 * 
 * <pre>
 * &lt;object&gt;
 * &lt;id&gt;100&lt;/id&gt;
 * &lt;name&gt;Jhon smith&lt;/name&gt;
 * &lt;phone&gt;130100000&lt;/phone&gt;
 * &lt;object&gt;
 * </pre>
 * 
 * XML??
 * 
 * <pre>
 * &lt;object id="100" name="Jhon smith" pone="130100000"&gt;
 * &lt;/object&gt;
 * </pre>
 * 
 * ?
 * 
 * @param e
 *            ??
 * @param keys
 *            ??
 */
public static void moveChildElementAsAttribute(Element e, String... keys) {
    NodeList nds = e.getChildNodes();
    for (Node node : toArray(nds)) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            e.removeChild(node); // 
        }
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;
        Element sub = (Element) node;
        String key = sub.getNodeName();
        if (keys.length == 0 || ArrayUtils.contains(keys, key)) {
            String value = nodeText(sub);
            e.setAttribute(key, value);
            e.removeChild(sub);
        }

    }
}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java

/** {@inheritDoc} */
public void moveInto(JavaSymbolName pageId, JavaSymbolName intoId) {
    Document document = getMenuDocument();

    // make the root element of the menu the one with the menu identifier
    // allowing for different decorations of menu
    Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP, (Element) document.getFirstChild());

    if (!rootElement.getNodeName().equals(GVNIX_MENU)) {
        throw new IllegalArgumentException(INVALID_XML);
    }//from   www.  ja v a  2  s .  c o m

    // check for existence of menu category by looking for the identifier
    // provided
    Element pageElement = XmlUtils.findFirstElement(ID_EXP.concat(pageId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(pageElement, PAGE.concat(pageId.getSymbolName()).concat(NOT_FOUND));

    Element intoElement = XmlUtils.findFirstElement(ID_EXP.concat(intoId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(intoElement, PAGE.concat(intoId.getSymbolName()).concat(NOT_FOUND));

    // parent element where remove menu entry element
    Element parent = (Element) pageElement.getParentNode();
    parent.removeChild(pageElement);

    // insert
    intoElement.appendChild(pageElement);

    writeXMLConfigIfNeeded(document);
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileC.java

protected void extendSignatureTag(Element signatureEl, Document originalData, SignatureFormat signatureFormat) {

    super.extendSignatureTag(signatureEl, originalData, signatureFormat);

    try {/*from ww  w.j a  va  2 s  . c  o  m*/

        Element qualifyingProperties = XMLUtils.getElement(signatureEl,
                "./ds:Object/xades:QualifyingProperties");
        Element unsignedPropertiesNode = XMLUtils.getElement(qualifyingProperties,
                "./xades:UnsignedProperties");
        Element unsignedSignaturePropertiesNode = XMLUtils.getElement(unsignedPropertiesNode,
                "./xades:UnsignedSignatureProperties");

        List<Node> toRemove = new ArrayList<Node>();

        if (unsignedSignaturePropertiesNode != null) {
            /* If we change a level C of a previous signature, we need to remove other node than level -T. */
            NodeList children = unsignedSignaturePropertiesNode.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node n = children.item(i);
                if (n.getNodeType() == Node.ELEMENT_NODE) {
                    Element e = (Element) n;
                    if (!"SignatureTimeStamp".equals(e.getLocalName())) {
                        toRemove.add(e);
                    }
                }
            }
        }

        /* We replace only if we go to level C, XL */
        if (toRemove.size() == 0 || signatureFormat == SignatureFormat.XAdES_C
                || signatureFormat == SignatureFormat.XAdES_XL || signatureFormat == SignatureFormat.XAdES_A) {

            for (Node e : toRemove) {
                LOG.warning("Remove element " + e.getLocalName());
                unsignedSignaturePropertiesNode.removeChild(e);
            }

            UnsignedPropertiesType unsignedPropertiesType = null;
            if (unsignedPropertiesNode != null) {
                unsignedPropertiesType = ((JAXBElement<UnsignedPropertiesType>) unmarshaller
                        .unmarshal(unsignedPropertiesNode)).getValue();
            } else {
                unsignedPropertiesType = xadesObjectFactory.createUnsignedPropertiesType();
            }

            extendSignatureTag(signatureEl, unsignedPropertiesType);

            if (unsignedPropertiesNode != null) {
                qualifyingProperties.removeChild(unsignedPropertiesNode);
            }

            marshaller.marshal(xadesObjectFactory.createUnsignedProperties(unsignedPropertiesType),
                    qualifyingProperties);

        }
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);

    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java

/** {@inheritDoc} */
public void moveBefore(JavaSymbolName pageId, JavaSymbolName beforeId) {
    Document document = getMenuDocument();

    // make the root element of the menu the one with the menu identifier
    // allowing for different decorations of menu
    Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP, (Element) document.getFirstChild());

    if (!rootElement.getNodeName().equals(GVNIX_MENU)) {
        throw new IllegalArgumentException(INVALID_XML);
    }//from  w  w  w.j  a v a 2s.c o  m

    // check for existence of menu category by looking for the identifier
    // provided
    Element pageElement = XmlUtils.findFirstElement(ID_EXP.concat(pageId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(pageElement, PAGE.concat(pageId.getSymbolName()).concat(NOT_FOUND));

    Element beforeElement = XmlUtils.findFirstElement(ID_EXP.concat(beforeId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(beforeElement, PAGE.concat(beforeId.getSymbolName()).concat(NOT_FOUND));

    // page parent element where remove menu entry element
    Element pageParentEl = (Element) pageElement.getParentNode();
    pageParentEl.removeChild(pageElement);

    // before parent element where execute insert before
    Element beforeParentEl = (Element) beforeElement.getParentNode();
    beforeParentEl.insertBefore(pageElement, beforeElement);

    writeXMLConfigIfNeeded(document);
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private Tuple<Collection<String>> updateWith(Document targetDocument, final Document updateDocument,
        List<FileUpdateOperation> fileUpdateOperations)
        throws XPathExpressionException, IOException, FedoraClientException {
    Element targetRoot = (Element) targetDocument.getElementsByTagName("Opus_Document").item(0);
    Element updateRoot = (Element) updateDocument.getElementsByTagName("Opus_Document").item(0);

    Set<String> distinctUpdateFieldList = new LinkedHashSet<>();
    NodeList updateFields = updateRoot.getChildNodes();
    for (int i = 0; i < updateFields.getLength(); i++) {
        distinctUpdateFieldList.add(updateFields.item(i).getNodeName());
    }/*from   w  w  w.  j  a va2  s.  co  m*/

    for (String fn : distinctUpdateFieldList) {
        // cannot use getElementsByTagName() here because it searches recursively
        for (Node victim : getChildNodesByName(targetRoot, fn)) {
            if (!victim.getLocalName().equals("File")) {
                targetRoot.removeChild(victim);
            }
        }
    }

    for (int i = 0; i < updateFields.getLength(); i++) {
        // Update node needs to be cloned, otherwise it will
        // be removed from updateFields by adoptNode().
        Node updateNode = updateFields.item(i).cloneNode(true);
        if (updateNode.hasChildNodes() && !updateNode.getLocalName().equals("File")) {
            targetDocument.adoptNode(updateNode);
            targetRoot.appendChild(updateNode);
        }
    }

    List<String> purgeDatastreamList = new LinkedList<>();
    if ((Boolean) xPath.evaluate("//File", updateDocument, XPathConstants.BOOLEAN)) {
        updateFileElementsInPlace(targetDocument, updateDocument, fileUpdateOperations, targetRoot, updateRoot,
                purgeDatastreamList);
    }

    targetDocument.normalizeDocument();
    return new Tuple<>(distinctUpdateFieldList, purgeDatastreamList);
}

From source file:com.enonic.vertical.adminweb.PageTemplateHandlerServlet.java

public void handlerForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems) throws VerticalAdminException {

    try {//from w w  w . j  a  va2  s . c o m
        User user = securityService.getLoggedInAdminConsoleUser();
        boolean createPageTemplate;
        boolean updateStyleSheet = formItems.getBoolean("updatestylesheet", true);
        boolean updateCSS = formItems.getBoolean("updatecss", false);
        String xmlData;
        Document doc;
        String cssStylesheetKey = null;

        String datasourcesXML;

        int menuKey = formItems.getInt("menukey");

        ResourceKey stylesheetKey = null;
        ResourceFile stylesheet = null;
        ResourceKey cssKey = null;
        boolean stylesheetValid = false;
        String cssKeyParam = request.getParameter("selectedcsskey");
        if (cssKeyParam != null && !"".equals(cssKeyParam)) {
            cssKey = new ResourceKey(cssKeyParam);
        }
        if (request.getParameter("selstylesheetkey") != null
                && request.getParameter("selstylesheetkey").length() > 0) {
            stylesheetKey = new ResourceKey(request.getParameter("selstylesheetkey"));
            formItems.putString("stylesheetkey", stylesheetKey.toString());
        }

        int key = formItems.getInt("key", -1);

        // If we have not selected a stylesheet yet
        if (stylesheetKey == null && cssKey == null && key == -1) {

            createPageTemplate = true;

            doc = XMLTool.createDocument("pagetemplates");
            Document dsDoc = XMLTool.createDocument("datasources");
            datasourcesXML = XMLTool.documentToString(dsDoc);
        } else {
            createPageTemplate = (key == -1);
            int pageTemplateKey;

            if (stylesheetKey == null && cssKey == null) // createPageTemplate = false
            {
                //   If we are editing an existing template
                pageTemplateKey = Integer.parseInt(request.getParameter("key"));
                xmlData = admin.getPageTemplate(pageTemplateKey);
                doc = XMLTool.domparse(xmlData);
                Element pagetemplateElem = XMLTool.getElement(doc.getDocumentElement(), "pagetemplate");
                Element stylesheetElem = XMLTool.getElement(pagetemplateElem, "stylesheet");
                stylesheetKey = new ResourceKey(stylesheetElem.getAttribute("stylesheetkey"));
            } else {
                // If we are making a new template
                doc = buildPageTemplateXML(formItems, key == -1);
                Element oldRoot = doc.getDocumentElement();
                String keyStr = oldRoot.getAttribute("key");
                if (keyStr != null && keyStr.length() > 0) {
                    pageTemplateKey = Integer.parseInt(keyStr);
                } else {
                    pageTemplateKey = -1;
                }
                Element newRoot = XMLTool.createElement(doc, "pagetemplates");
                doc.replaceChild(newRoot, oldRoot);
                newRoot.appendChild(oldRoot);
                updateStyleSheet = stylesheetKey != null;
                if (!updateStyleSheet) {
                    Element elem = XMLTool.getElement(oldRoot, "stylesheet");
                    String styleSheetKeyStr = elem.getAttribute("stylesheetkey");
                    if (styleSheetKeyStr.length() > 0) {
                        stylesheetKey = new ResourceKey(styleSheetKeyStr);
                    }
                }
            }

            Element cssElem = (Element) XMLTool.selectNode(doc, "/pagetemplates/pagetemplate/css");
            if (cssElem != null) {
                if (updateCSS && cssKey == null) {
                    cssElem.getParentNode().removeChild(cssElem);
                } else {
                    cssStylesheetKey = cssElem.getAttribute("stylesheetkey");
                }
            }

            Element ptdElem = (Element) XMLTool.selectNode(doc, "/pagetemplates/pagetemplate/pagetemplatedata");
            Element dselem = XMLTool.getElement(ptdElem, "datasources");
            if (dselem != null) {
                Document dsDoc = XMLTool.createDocument();
                dsDoc.appendChild(dsDoc.importNode(dselem, true));
                datasourcesXML = XMLTool.documentToString(dsDoc);
            } else {
                Document dsDoc = XMLTool.createDocument("datasources");
                datasourcesXML = XMLTool.documentToString(dsDoc);
            }

            if (!updateStyleSheet) {
                // Insert valuename attributes all parameters
                Element[] pagetemplateparamElems = XMLTool.getElements(ptdElem, "pagetemplateparameter");
                for (Element pagetemplateparamElem : pagetemplateparamElems) {
                    String keyStr = pagetemplateparamElem.getAttribute("value");
                    if (keyStr != null && keyStr.length() > 0) {
                        String type = pagetemplateparamElem.getAttribute("type");
                        if ("category".equals(type)) {
                            int categoryKey = Integer.parseInt(keyStr);
                            String name = admin.getCategoryName(categoryKey);
                            pagetemplateparamElem.setAttribute("valuename", name);
                        } else if ("page".equals(type)) {
                            int menuItemKey = Integer.parseInt(keyStr);
                            String name = admin.getMenuItemName(menuItemKey);
                            pagetemplateparamElem.setAttribute("valuename", name);
                        } else if ("resource".equals(type)) {
                            pagetemplateparamElem.setAttribute("valuename", keyStr);
                        }
                    }
                }
            }

            String menuItemsXML = admin.getMenuItemsByPageTemplates(user, new int[] { pageTemplateKey });
            Document menuItemsDoc = XMLTool.domparse(menuItemsXML);
            XMLTool.mergeDocuments(doc, menuItemsDoc, true);
        }

        if (stylesheetKey != null && ((createPageTemplate && cssKey == null) || updateStyleSheet)) {

            Map<String, Element> elemMap = new HashMap<String, Element>();
            Element root = doc.getDocumentElement();
            if (updateStyleSheet) {
                // Remove all parameters from xml
                root = XMLTool.getElement(root, "pagetemplate");
                Element pageTemplateParamterRootElement = XMLTool.getElement(root, "pagetemplateparameters");
                Element[] pageTemplateParameterElems = XMLTool.getElements(pageTemplateParamterRootElement,
                        "pagetemplateparameter");
                for (Element elem : pageTemplateParameterElems) {
                    String name = XMLTool.getElementText(XMLTool.getElement(elem, "name"));
                    elemMap.put(name, elem);
                }
                root.removeChild(pageTemplateParamterRootElement);
                pageTemplateParamterRootElement = XMLTool.getElement(root, "pagetemplatedata");
                pageTemplateParameterElems = XMLTool.getElements(pageTemplateParamterRootElement,
                        "pagetemplateparameter");
                for (Element elem1 : pageTemplateParameterElems) {
                    String name = elem1.getAttribute("name");
                    elemMap.put(name, elem1);
                    pageTemplateParamterRootElement.removeChild(elem1);
                }
            }
            Element stylesheetParams = XMLTool.createElement(doc, root, "pagetemplateparameters");

            Element pagetemplatedataElem = XMLTool.getElement(root, "pagetemplatedata");
            if (pagetemplatedataElem == null) {
                pagetemplatedataElem = XMLTool.createElement(doc, root, "pagetemplatedata");
            }

            stylesheet = resourceService.getResourceFile(stylesheetKey);
            if (stylesheet != null) {
                Document stylesheetDoc = null;
                try {
                    stylesheetDoc = stylesheet.getDataAsXml().getAsDOMDocument();
                    stylesheetValid = true;
                } catch (XMLException e) {
                }
                if (stylesheetDoc != null) {
                    Element[] paramElems = XMLTool.getElements(stylesheetDoc.getDocumentElement(), "xsl:param");
                    for (Element paramElem : paramElems) {
                        Element typeElem = XMLTool.getElement(paramElem, "type");
                        Element tempElem;
                        String name = paramElem.getAttribute("name");
                        if (typeElem != null) {
                            String type = XMLTool.getElementText(typeElem);
                            if ("object".equals(type) || "region".equals(type)) {
                                Element elem = elemMap.get(name);
                                if (elem != null && elem.getAttribute("type").length() == 0) {
                                    stylesheetParams.appendChild(elem);
                                } else {
                                    tempElem = XMLTool.createElement(doc, stylesheetParams,
                                            "pagetemplateparameter");
                                    XMLTool.createElement(doc, tempElem, "name", name);
                                }
                            } else {
                                if (elemMap.containsKey(name)) {
                                    Element elem = elemMap.get(name);
                                    String elemType = elem.getAttribute("type");
                                    if (elemType.length() == 0) {
                                        elem.setAttribute("name", name);
                                        XMLTool.removeChildNodes(elem, true);
                                    }
                                    elem.setAttribute("type", type);
                                    pagetemplatedataElem.appendChild(elem);
                                } else {
                                    tempElem = XMLTool.createElement(doc, pagetemplatedataElem,
                                            "pagetemplateparameter");
                                    tempElem.setAttribute("name", name);
                                    tempElem.setAttribute("type", type);
                                }
                            }
                        } else {
                            // Alle vanlige parametere, spesifisert som as="xs:string", e.l. i XSL'en.
                            if (elemMap.containsKey(name)) {
                                Element elem = elemMap.get(name);
                                String type = elem.getAttribute("type");
                                if (type.length() == 0) {
                                    elem.setAttribute("name", name);
                                    XMLTool.removeChildNodes(elem, true);
                                } else {
                                    elem.removeAttribute("type");
                                    elem.removeAttribute("valuename");
                                }
                                pagetemplatedataElem.appendChild(elem);
                            } else {
                                tempElem = XMLTool.createElement(doc, pagetemplatedataElem,
                                        "pagetemplateparameter");
                                tempElem.setAttribute("name", name);
                            }
                        }
                    }
                }
            }
        }

        if (stylesheet == null && stylesheetKey != null) {
            stylesheet = resourceService.getResourceFile(stylesheetKey);
        }

        if (stylesheet != null) {
            Document stylesheetDoc = null;
            try {
                stylesheetDoc = stylesheet.getDataAsXml().getAsDOMDocument();
                stylesheetValid = true;
            } catch (XMLException e) {
            }
            if (stylesheetDoc != null) {
                Element tmpElem = XMLTool.createElement(doc.getDocumentElement(), "resource");
                tmpElem.appendChild(doc.importNode(stylesheetDoc.getDocumentElement(), true));
            }
        }

        // Get content types for this site
        XMLTool.mergeDocuments(doc, admin.getContentTypes(false).getAsDOMDocument(), true);

        DOMSource xmlSource = new DOMSource(doc);

        Source xslSource = AdminStore.getStylesheet(session, "pagetemplate_form.xsl");

        HashMap<String, Object> parameters = new HashMap<String, Object>();
        addCommonParameters(admin, user, request, parameters, -1, menuKey);

        if (cssStylesheetKey != null) {
            parameters.put("cssStylesheetKey", cssStylesheetKey);
            parameters.put("cssStylesheetExist",
                    resourceService.getResourceFile(new ResourceKey(cssStylesheetKey)) == null ? "false"
                            : "true");
        }

        ResourceKey defaultCSSKey = admin.getDefaultCSSByMenu(menuKey);
        if (defaultCSSKey != null) {
            parameters.put("defaultcsskey", defaultCSSKey.toString());
            parameters.put("defaultcssExist",
                    resourceService.getResourceFile(defaultCSSKey) == null ? "false" : "true");
        }

        if (createPageTemplate) {
            parameters.put("create", "1");
        } else {
            parameters.put("create", "0");
        }

        parameters.put("page", String.valueOf(request.getParameter("page")));
        datasourcesXML = StringUtil.formatXML(datasourcesXML, 2);
        parameters.put("datasources", datasourcesXML);

        parameters.put("menukey", formItems.getString("menukey"));
        parameters.put("selectedtabpageid", formItems.getString("selectedtabpageid", "none"));

        if (stylesheetKey != null) {
            parameters.put("selstylesheetkey", stylesheetKey.toString());
            parameters.put("selstylesheetExist", stylesheet == null ? "false" : "true");
            parameters.put("selstylesheetValid", stylesheetValid ? "true" : "false");

        }

        addAccessLevelParameters(user, parameters);

        UserEntity defaultRunAsUser = siteDao.findByKey(formItems.getInt("menukey")).resolveDefaultRunAsUser();
        String defaultRunAsUserName = "NA";
        if (defaultRunAsUser != null) {
            defaultRunAsUserName = defaultRunAsUser.getDisplayName();
        }
        parameters.put("defaultRunAsUser", defaultRunAsUserName);

        transformXML(session, response.getWriter(), xmlSource, xslSource, parameters);
    } catch (TransformerException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 10, "XSLT error: %t", e);
    } catch (IOException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 20, "I/O error: %t", e);
    }
}