Example usage for org.w3c.dom Element getOwnerDocument

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

Introduction

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

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:be.fedict.eid.idp.protocol.ws_federation.AbstractWSFederationMetadataHttpServlet.java

private void writeMetadata(HttpServletRequest request, IdentityProviderConfiguration configuration,
        OutputStream outputStream) throws JAXBException, ServletException, ParserConfigurationException,
        CertificateEncodingException, TransformerFactoryConfigurationError, TransformerException, IOException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {

    String location = getLocation(request);

    EntityDescriptor entityDescriptor = Saml2Util.buildXMLObject(EntityDescriptor.class,
            EntityDescriptor.DEFAULT_ELEMENT_NAME);
    entityDescriptor.setEntityID(location);
    entityDescriptor.setID("saml-metadata-" + UUID.randomUUID().toString());

    @SuppressWarnings("unchecked")
    XMLObjectBuilder<SecurityTokenService> builder = Configuration.getBuilderFactory()
            .getBuilder(SecurityTokenService.TYPE_NAME);
    SecurityTokenService securityTokenService = builder.buildObject(RoleDescriptor.DEFAULT_ELEMENT_NAME,
            SecurityTokenService.TYPE_NAME);
    entityDescriptor.getRoleDescriptors().add(securityTokenService);

    securityTokenService.addSupportedProtocol("http://docs.oasis-open.org/wsfed/federation/200706");

    PassiveRequestorEndpoint passiveRequestorEndpoint = Saml2Util.buildXMLObject(PassiveRequestorEndpoint.class,
            PassiveRequestorEndpoint.DEFAULT_ELEMENT_NAME);
    securityTokenService.getPassiveRequestorEndpoints().add(passiveRequestorEndpoint);

    EndpointReference endpoint = Saml2Util.buildXMLObject(EndpointReference.class,
            EndpointReference.ELEMENT_NAME);
    passiveRequestorEndpoint.setEndpointReference(endpoint);

    Address address = Saml2Util.buildXMLObject(Address.class, Address.ELEMENT_NAME);
    endpoint.setAddress(address);/*from  ww w . j av  a  2s .c  om*/
    address.setValue(location);

    IdPIdentity identity = configuration.findIdentity();
    try {
        if (null != identity) {

            KeyDescriptor keyDescriptor = Saml2Util.buildXMLObject(KeyDescriptor.class,
                    KeyDescriptor.DEFAULT_ELEMENT_NAME);
            securityTokenService.getKeyDescriptors().add(keyDescriptor);
            keyDescriptor.setUse(UsageType.SIGNING);

            org.opensaml.xml.signature.KeyInfo keyInfo = Saml2Util.buildXMLObject(
                    org.opensaml.xml.signature.KeyInfo.class,
                    org.opensaml.xml.signature.KeyInfo.DEFAULT_ELEMENT_NAME);
            keyDescriptor.setKeyInfo(keyInfo);

            KeyInfoHelper.addCertificate(keyInfo,
                    (X509Certificate) identity.getPrivateKeyEntry().getCertificate());
        }
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("opensaml2 certificate encoding error: " + e.getMessage(), e);
    }

    // claims
    ClaimTypesOffered claimTypesOffered = Saml2Util.buildXMLObject(ClaimTypesOffered.class,
            ClaimTypesOffered.DEFAULT_ELEMENT_NAME);
    securityTokenService.setClaimTypesOffered(claimTypesOffered);

    List<ClaimType> claimTypes = claimTypesOffered.getClaimTypes();

    for (AttributeConfig attribute : configuration
            .getAttributes(AbstractWSFederationProtocolService.WS_FED_PROTOCOL_ID)) {
        addClaimType(attribute.getUri(), attribute.getName(), attribute.getDescription(), claimTypes);
    }

    Element element;
    if (null != identity) {

        LOG.debug("sign WS-Federation Metadata");
        element = Saml2Util.signAsElement(entityDescriptor, entityDescriptor, identity.getPrivateKeyEntry());
    } else {

        LOG.warn("WS-Federation Metadata NOT signed!");
        element = Saml2Util.marshall(entityDescriptor);
    }

    Saml2Util.writeDocument(element.getOwnerDocument(), outputStream);
}

From source file:com.enonic.esl.xml.XMLTool.java

public static Element createElementBeforeChild(Element root, Element child, String name, String text) {

    if (name == null) {
        throw new XMLToolException("Element name cannot be null!");
    } else if (name.trim().length() == 0) {
        throw new XMLToolException("Element name has to contain at least one character!");
    }/*ww  w  . j a  v  a  2  s .  co m*/

    Document doc = root.getOwnerDocument();
    Element elem = doc.createElement(name);
    if (text != null) {
        Text textNode = doc.createTextNode(text);
        elem.appendChild(textNode);
    }
    root.insertBefore(elem, child);

    return elem;
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

protected Element encodeRef(Element parent, Entity entity) {
    Element ref = parent.getOwnerDocument().createElement(entity == null ? ELEMENT_NULL_REF : ELEMENT_REF);
    if (entity != null)
        ref.setAttribute(ATTR_ID, ior(entity));

    // IMPORTANT: for xml transformer not to omit the closing tag, otherwise dojo is confused
    ref.setTextContent(EMPTY_TEXT);//from w ww  .  jav  a2s  .co  m
    parent.appendChild(ref);
    return ref;
}

From source file:com.dragoniade.deviantart.deviation.SearchRss.java

public List<Deviation> search(ProgressDialog progress, Collection collection) {
    if (user == null) {
        throw new IllegalStateException("You must set the user before searching.");
    }//  w ww  .j  a va 2  s  .c  o m
    if (search == null) {
        throw new IllegalStateException("You must set the search type before searching.");
    }
    if (total < 0) {
        progress.setText("Fetching total (0)");
        total = retrieveTotal(progress, collection);
        progress.setText("Total: " + total);
    }

    String searchQuery = search.getSearch().replace("%username%", user);
    String queryString = "http://backend.deviantart.com/rss.xml?q=" + searchQuery
            + (collection == null ? "" : "/" + collection.getId()) + "&type=deviation&offset=" + offset;
    GetMethod method = new GetMethod(queryString);
    List<Deviation> results = new ArrayList<Deviation>(OFFSET);
    try {
        int sc = -1;
        do {
            sc = client.executeMethod(method);
            if (sc != 200) {
                LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex);

                int res = DialogHelper.showConfirmDialog(owner,
                        "An error has occured when contacting deviantART : error " + sc + ". Try again?",
                        "Continue?", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.NO_OPTION) {
                    return null;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }
        } while (sc != 200);

        XmlToolkit toolkit = XmlToolkit.getInstance();

        Element responses = toolkit.parseDocument(method.getResponseBodyAsStream());
        method.releaseConnection();

        HashMap<String, String> prefixes = new HashMap<String, String>();
        prefixes.put("media", responses.getOwnerDocument().lookupNamespaceURI("media"));
        NamespaceContext context = toolkit.getNamespaceContext(prefixes);

        List<?> deviations = toolkit.getMultipleNodes(responses, "channel/item");
        if (deviations.size() == 0) {
            return results;
        }

        for (Object obj : deviations) {
            Element deviation = (Element) obj;

            Deviation da = new Deviation();
            da.setId(getId(toolkit.getNodeAsString(deviation, "guid")));
            da.setArtist(toolkit.getNodeAsString(deviation, "media:credit", context));
            da.setCategory(toolkit.getNodeAsString(deviation, "media:category", context));
            da.setTitle(toolkit.getNodeAsString(deviation, "media:title", context));
            da.setUrl(toolkit.getNodeAsString(deviation, "link"));
            da.setTimestamp(parseDate(toolkit.getNodeAsString(deviation, "pubDate")));
            da.setMature(!"nonadult".equals(toolkit.getNodeAsString(deviation, "media:rating", context)));
            da.setCollection(collection);

            Element documentNode = (Element) toolkit.getSingleNode(deviation,
                    "media:content[@medium='document']", context);
            Element imageNode = (Element) toolkit.getSingleNode(deviation, "media:content[@medium='image']",
                    context);
            Element videoNode = (Element) toolkit.getSingleNode(deviation, "media:content[@medium='video']",
                    context);

            if (imageNode != null) {
                String content = imageNode.getAttribute("url");
                String filename = Deviation.extractFilename(content);
                da.setImageDownloadUrl(content);
                da.setImageFilename(filename);

                da.setResolution(imageNode.getAttribute("width") + "x" + imageNode.getAttribute("height"));
            }

            if (documentNode != null) {
                String content = documentNode.getAttribute("url");
                String filename = Deviation.extractFilename(content);
                da.setDocumentDownloadUrl(content);
                da.setDocumentFilename(filename);
            }

            if (videoNode != null) {
                String content = videoNode.getAttribute("url");
                if (!content.endsWith("/")) {
                    content = content + "/";
                }
                String filename = Deviation.extractFilename(content);
                da.setDocumentDownloadUrl(content);
                da.setDocumentFilename(filename);
            }

            results.add(da);
        }
        offset = offset + deviations.size();
        return results;
    } catch (HttpException e) {
        DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    } catch (IOException e) {
        DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }
}

From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java

private void validateToken(Element tokenElement, String expectedAudience,
        IdentityProviderConfiguration identityProviderConfiguration) throws Exception {
    List<X509Certificate> certificateChain = identityProviderConfiguration.getIdentityCertificateChain();
    if (certificateChain.isEmpty()) {
        throw new SecurityException("no eID IdP service identity configured");
    }//from   www  .  ja  v a  2 s .c  o m

    Element nsElement = tokenElement.getOwnerDocument().createElement("nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion");
    LOG.debug("token element: " + tokenElement.getLocalName());
    LOG.debug("token element namespace: " + tokenElement.getNamespaceURI());
    LOG.debug("token: " + toString(tokenElement));

    // fix for recent versions of Apache xmlsec.
    tokenElement.setIdAttribute("ID", true);

    Element signatureElement = (Element) XPathAPI.selectSingleNode(tokenElement, "ds:Signature", nsElement);
    if (null == signatureElement) {
        throw new SecurityException("missing XML signature");
    }

    XMLSignature xmlSignature = new XMLSignature(signatureElement, "");
    KeyInfo keyInfo = xmlSignature.getKeyInfo();
    X509Certificate actualCertificate = keyInfo.getX509Certificate();
    boolean signatureResult = xmlSignature.checkSignatureValue(actualCertificate);
    if (false == signatureResult) {
        throw new SecurityException("invalid XML signature");
    }
    LOG.debug("XML signature OK");

    X509Certificate serviceCertificate = certificateChain.get(0);
    if (false == Arrays.equals(serviceCertificate.getEncoded(), actualCertificate.getEncoded())) {
        throw new SecurityException("SAML signing certificate different from eID IdP service identity");
    }
    LOG.debug("SAML signer OK");

    String actualIssuer = XPathAPI.selectSingleNode(tokenElement, "saml2:Issuer/text()", nsElement)
            .getNodeValue();
    String serviceIssuer = identityProviderConfiguration.getDefaultIssuer();
    if (false == actualIssuer.equals(serviceIssuer)) {
        LOG.debug("actual issuer: " + actualIssuer);
        LOG.debug("service issuer: " + serviceIssuer);
        throw new SecurityException("wrong SAML issuer");
    }
    LOG.debug("SAML issuer OK");

    if (null != expectedAudience) {
        String audience = XPathAPI
                .selectSingleNode(tokenElement,
                        "saml2:Conditions/saml2:AudienceRestriction/saml2:Audience/text()", nsElement)
                .getNodeValue();
        if (false == expectedAudience.equals(audience)) {
            LOG.debug("expected audience: " + expectedAudience);
            LOG.debug("actual audience: " + audience);
            throw new SecurityException("incorrect SAML audience");
        }
        LOG.debug("SAML Audience OK");
    } else {
        LOG.warn("SAML audience restriction not checked");
    }

    String authnContextClassRef = XPathAPI
            .selectSingleNode(tokenElement,
                    "saml2:AuthnStatement/saml2:AuthnContext/saml2:AuthnContextClassRef/text()", nsElement)
            .getNodeValue();
    LOG.debug("AuthnContextClassRef: " + authnContextClassRef);
    SamlAuthenticationPolicy samlAuthenticationPolicy = SamlAuthenticationPolicy
            .getAuthenticationPolicy(authnContextClassRef);
    if (SamlAuthenticationPolicy.AUTHENTICATION != samlAuthenticationPolicy
            && SamlAuthenticationPolicy.AUTHENTICATION_WITH_IDENTIFICATION != samlAuthenticationPolicy) {
        throw new SecurityException("wrong SAML authentication policy: " + samlAuthenticationPolicy);
    }

    String notBeforeStr = XPathAPI.selectSingleNode(tokenElement, "saml2:Conditions/@NotBefore", nsElement)
            .getNodeValue();
    String notOnOrAfterStr = XPathAPI
            .selectSingleNode(tokenElement, "saml2:Conditions/@NotOnOrAfter", nsElement).getNodeValue();
    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser();
    DateTime notBefore = dateTimeFormatter.parseDateTime(notBeforeStr);
    DateTime notOnOrAfter = dateTimeFormatter.parseDateTime(notOnOrAfterStr);
    DateTime now = new DateTime();
    if (now.isBefore(notBefore)) {
        throw new SecurityException("SAML assertion in future");
    }
    if (now.isAfter(notOnOrAfter)) {
        throw new SecurityException("SAML assertion expired");
    }
    LOG.debug("SAML timestamp OK");
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

@Override
public String process(Set<Entity> entities)
        throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
    Element root = newDocument(MAPPING_ROOT_ELEMENT_INSTANCE);
    Document doc = root.getOwnerDocument();
    for (Entity entity : entities) {
        Element pair = doc.createElement(PAIR_ELEMENT);
        root.appendChild(pair);//from  w  w w. j  av a  2 s.  co  m
        encodeEntityInstance(new HashSet<Entity>(), entity, pair, false, getMetaClass(entity), null);
        encodeEntityInstance(new HashSet<Entity>(), entity, pair, false, getMetaClass(entity), null);
    }
    return documentToString(doc);
}

From source file:com.qut.middleware.esoe.sso.plugins.artifact.impl.ArtifactProcessorImpl.java

public String registerArtifact(Element artifactDocument, String audience) throws ArtifactBindingException {
    try {//w ww.  ja v  a  2s .c om
        byte[] messageHandle = new byte[20];
        this.random.nextBytes(messageHandle);

        byte[] document = this.artifactResponseMarshaller.generateOutput(artifactDocument.getOwnerDocument(),
                null);

        Artifact artifact = new Artifact(this.nodeIndex, this.sourceID, messageHandle, audience, document);
        this.artifactDao.storeArtifact(artifact);

        return artifact.toBase64Artifact();
    } catch (MarshallerException e) {
        throw new ArtifactBindingException(
                "Marshalling failed while registering artifact. Unable to continue. Error: " + e.getMessage(),
                e);
    }
}

From source file:ca.inverse.sogo.engine.source.SOGoPropertyConverter.java

protected Property _convertIsRecurring(Element e) {
    Text textNode = (Text) e.getFirstChild();
    String isRecurringValue = textNode.getNodeValue();
    if (!Boolean.valueOf(isRecurringValue).booleanValue() && Integer.valueOf(isRecurringValue).intValue() < 1)
        return null;

    Element rootElement = e.getOwnerDocument().getDocumentElement();
    StringBuffer propertyValue = new StringBuffer();

    String sifRecurrenceType = getSifValue(rootElement, "RecurrenceType");
    if (sifRecurrenceType != null) {
        String iCalRecurrenceType = (String) this.sif2ICalDirectMappings
                .get("rrule.RecurrenceType." + sifRecurrenceType);
        propertyValue.append("FREQ=").append(iCalRecurrenceType);

        String patternEndDate = getSifValue(rootElement, "PatternEndDate");
        if (patternEndDate == null) {
            String occurences = getSifValue(rootElement, "Occurrences");
            if (occurences != null && (Integer.valueOf(occurences).intValue() > 0))
                propertyValue.append(";COUNT=").append(occurences);
        } else {/*from  w w w .j  a  v  a 2 s  . co m*/

            //             if ( patternEndDate != null )
            propertyValue.append(";UNTIL=").append(patternEndDate);
        }

        //             boolean noEndDate = "1".equals ( getSifValue ( rootElement, "NoEndDate" ) );

        int interval = 0, dayOfWeekMask = 0, dayOfMonth = 0, instance = 0, monthOfYear = 0;

        switch (Integer.valueOf(sifRecurrenceType).intValue()) {
        // olRecursDaily
        case 0:
            interval = Integer.valueOf(getSifValue(rootElement, "Interval")).intValue();
            break;
        // olRecursWeekly
        case 1:
            interval = Integer.valueOf(getSifValue(rootElement, "Interval")).intValue();
            dayOfWeekMask = Integer.valueOf(getSifValue(rootElement, "DayOfWeekMask")).intValue();
            break;
        // olRecursMonthly
        case 2:
            interval = Integer.valueOf(getSifValue(rootElement, "Interval")).intValue();
            dayOfWeekMask = Integer.valueOf(getSifValue(rootElement, "DayOfWeekMask")).intValue();
            dayOfMonth = Integer.valueOf(getSifValue(rootElement, "DayOfMonth")).intValue();
            break;
        // olRecursMonthNth
        case 3:
            interval = Integer.valueOf(getSifValue(rootElement, "Interval")).intValue();
            instance = Integer.valueOf(getSifValue(rootElement, "Instance")).intValue();
            dayOfWeekMask = Integer.valueOf(getSifValue(rootElement, "DayOfWeekMask")).intValue();
            break;
        // olRecursYearly
        case 5:
            monthOfYear = Integer.valueOf(getSifValue(rootElement, "MonthOfYear")).intValue();
            dayOfMonth = Integer.valueOf(getSifValue(rootElement, "DayOfMonth")).intValue();
            break;
        // olRecursYearNth
        case 6:
            instance = Integer.valueOf(getSifValue(rootElement, "Instance")).intValue();
            dayOfWeekMask = Integer.valueOf(getSifValue(rootElement, "DayOfWeekMask")).intValue();
            monthOfYear = Integer.valueOf(getSifValue(rootElement, "MonthOfYear")).intValue();
            break;
        }

        if (interval > 1)
            propertyValue.append(";INTERVAL=").append(interval);

        if (instance > 0)
            propertyValue.append(";BYSETPOS=").append(instance > 4 ? -1 : instance);

        if (dayOfWeekMask > 0) {
            StringBuffer byDayBuffer = new StringBuffer();
            for (int i = 1; i <= 64; i <<= 1) {
                if ((dayOfWeekMask & i) == i) {
                    String iCalWkDay = (String) this.sif2ICalDirectMappings.get("rrule.DayOfWeekMask." + i);
                    if (byDayBuffer.length() > 0)
                        byDayBuffer.append(',');
                    byDayBuffer.append(iCalWkDay);
                }
            }
            if (byDayBuffer.length() > 0)
                propertyValue.append(";BYDAY=").append(byDayBuffer);
        }

        if (monthOfYear > 0)
            propertyValue.append(";BYMONTH=").append(monthOfYear);

        if (dayOfMonth > 0)
            propertyValue.append(";BYMONTHDAY=").append(dayOfMonth);

    } else {
        /* no recurrence type specified - won't create RRULE */
        return null;
    }

    return new Property("RRULE", propertyValue.toString());
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

private static void jsonToXml(Object object, String objectKey, Element parentElement, boolean modifyElement,
        boolean includeDataType, boolean compactArray, String arrayChildrenTag) throws JSONException {
    Engine.logBeans.trace("Converting JSON to XML: object=" + object + "; objectKey=\"" + objectKey + "\"");

    Document doc = parentElement.getOwnerDocument();

    if ("_attachments".equals(parentElement.getNodeName()) && "item".equals(arrayChildrenTag)
            && object instanceof JSONObject) {
        // special case when retrieving attachments with Couch : attachment name is the object key
        ((JSONObject) object).put("name", objectKey);
        objectKey = "attachment";
    }//ww  w .  ja v a 2s. com

    // Normalize object key
    String originalObjectKey = objectKey;
    if (objectKey != null) {
        objectKey = StringUtils.normalize(objectKey);
    }

    // JSON object value case
    if (object instanceof JSONObject) {
        JSONObject json = (JSONObject) object;

        Element element = doc.createElement(objectKey == null ? "object" : objectKey);
        if (objectKey != null && !objectKey.equals(originalObjectKey)) {
            element.setAttribute("originalKeyName", originalObjectKey);
        }

        if (compactArray || modifyElement) {
            if (objectKey == null) {
                element = parentElement;
            } else {
                parentElement.appendChild(element);
            }
        } else {
            parentElement.appendChild(element);
        }

        if (includeDataType) {
            element.setAttribute("type", "object");
        }

        String[] keys = new String[json.length()];

        int index = 0;
        for (Iterator<String> i = GenericUtils.cast(json.keys()); i.hasNext();) {
            keys[index++] = i.next();
        }

        Arrays.sort(keys);

        for (String key : keys) {
            jsonToXml(json.get(key), key, element, false, includeDataType, compactArray, arrayChildrenTag);
        }
    }
    // Array value case
    else if (object instanceof JSONArray) {
        JSONArray array = (JSONArray) object;
        int len = array.length();

        Element arrayElement = parentElement;
        String arrayItemObjectKey = arrayChildrenTag;
        if (!(compactArray || modifyElement)) {
            arrayElement = doc.createElement(objectKey == null ? "array" : objectKey);
            if (objectKey != null && !objectKey.equals(originalObjectKey)) {
                arrayElement.setAttribute("originalKeyName", originalObjectKey);
            }
            parentElement.appendChild(arrayElement);

            if (includeDataType) {
                arrayElement.setAttribute("type", "array");
                arrayElement.setAttribute("length", "" + len);
            }
        } else if (objectKey != null) {
            arrayItemObjectKey = objectKey;
        }

        for (int i = 0; i < len; i++) {
            Object itemArray = array.get(i);
            jsonToXml(itemArray, arrayItemObjectKey, arrayElement, false, includeDataType, compactArray,
                    arrayChildrenTag);
        }
    } else {
        Element element = doc.createElement(objectKey == null ? "value" : objectKey);
        if (objectKey != null && !objectKey.equals(originalObjectKey)) {
            element.setAttribute("originalKeyName", originalObjectKey);
        }

        parentElement.appendChild(element);

        if (JSONObject.NULL.equals(object)) {
            object = null;
        }

        if (object != null) {
            Text text = doc.createTextNode(object.toString());
            element.appendChild(text);
        }

        if (includeDataType) {
            String objectType = object == null ? "null" : object.getClass().getCanonicalName();
            if (objectType.startsWith("java.lang.")) {
                objectType = objectType.substring(10);
            }
            element.setAttribute("type", objectType.toLowerCase());
        }
    }

}

From source file:com.enonic.cms.web.portal.services.ContentServicesBase.java

private Element createXPathElements(Element parentElement, String xpath, int startIdx) {
    Document doc = parentElement.getOwnerDocument();

    // First, create the elements in the xpath:
    String[] xpathSplit = StringUtil.splitString(xpath, '/');
    Element tmpElem = null;/*from  w  w  w.  j a v  a2  s .  com*/

    for (int j = startIdx; j < xpathSplit.length; ++j) {
        if (tmpElem == null) {
            if (j != (xpathSplit.length - 1) && XMLTool.getElement(parentElement, xpathSplit[j]) != null) {
                tmpElem = XMLTool.getElement(parentElement, xpathSplit[j]);
            } else {
                tmpElem = XMLTool.createElement(doc, parentElement, xpathSplit[j]);
            }
        } else {
            if (j != (xpathSplit.length - 1) && XMLTool.getElement(tmpElem, xpathSplit[j]) != null) {
                tmpElem = XMLTool.getElement(tmpElem, xpathSplit[j]);
            } else {
                tmpElem = XMLTool.createElement(doc, tmpElem, xpathSplit[j]);
            }
        }
    }

    return tmpElem;
}