Example usage for org.w3c.dom Element getAttributeNode

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

Introduction

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

Prototype

public Attr getAttributeNode(String name);

Source Link

Document

Retrieves an attribute node by name.

Usage

From source file:org.getwheat.harvest.library.dom.DomHelper.java

private boolean isValid(final Element element) {
    boolean value = false;
    if (element != null) {
        if (element.hasAttribute(VALUE_NIL)
                && VALUE_TRUE.equals(element.getAttributeNode(VALUE_NIL).getNodeValue())) {
            value = false;/* w ww .j  av a2s.  co m*/
        } else {
            final Node child = element.getFirstChild();
            value = child != null;
        }
    }
    return value;
}

From source file:curam.molsa.test.customfunctions.MOLSATestDatastore.java

/**
 * this is to map the attribute//  w w w  .  ja  v  a2  s  . c  o m
 * @param entityXMLElement
 * @param dsEntity
 * @param knownAttributeName
 */
private void mapAttribute(final Element entityXMLElement, final Entity dsEntity,
        final String knownAttributeName) {

    final Attr attributeNode = entityXMLElement.getAttributeNode(knownAttributeName);

    if (attributeNode != null) {
        final String attributeValue = attributeNode.getValue();
        dsEntity.setAttribute(knownAttributeName, attributeValue);

    }

}

From source file:org.opencredo.esper.integration.config.xml.InboundChannelAdapterParser.java

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    String channelRef = element.getAttribute("channel");
    Assert.hasText(channelRef, "channel attribute must be provided");
    builder.addConstructorArgReference(channelRef);

    Element eplElements = DomUtils.getChildElementByTagName(element, "epl");

    if (eplElements != null) {
        builder.addConstructorArgValue(eplElements.getTextContent());
    } else {/*from   w  w w .j av a  2s  .co m*/
        builder.addConstructorArgValue(null);
    }

    Attr templateNameNode = element.getAttributeNode("template-name");
    if (templateNameNode != null) {
        builder.addPropertyValue("templateName", templateNameNode.getTextContent());
    }
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

protected void mergeMetaData(Document templateDocument, Element templteElement, Element element) {
    if (element.getAttributeNode(ViewXmlConstants.ATTRIBUTE_METADATA) != null) {
        templteElement.setAttribute(ViewXmlConstants.ATTRIBUTE_METADATA,
                element.getAttribute(ViewXmlConstants.ATTRIBUTE_METADATA));
    }/*from  w  w  w  . ja v  a  2s .  c  om*/

    Element templateMetaDataElement = findPropertyElement(templteElement, ViewXmlConstants.ATTRIBUTE_METADATA);
    Element metaDataElement = findPropertyElement(element, ViewXmlConstants.ATTRIBUTE_METADATA);
    if (metaDataElement != null) {
        if (templateMetaDataElement == null) {
            templateMetaDataElement = templateDocument.createElement(XmlConstants.PROPERTY);
            templateMetaDataElement.setAttribute(XmlConstants.ATTRIBUTE_NAME,
                    ViewXmlConstants.ATTRIBUTE_METADATA);
            templteElement.appendChild(templateMetaDataElement);
        }

        for (Element metaPropertyElement : DomUtils.getChildrenByTagName(metaDataElement,
                XmlConstants.PROPERTY)) {
            Element clonedElement = (Element) templateDocument.importNode(metaPropertyElement, true);
            templateMetaDataElement.appendChild(clonedElement);
        }
    }
}

From source file:net.bpelunit.util.XMLUtilTest.java

@Test
public void testGetXPathForElement() throws Exception {
    Document xml = XMLUtil.parseXML(getClass().getResourceAsStream("GetXPathForElement.xml"));

    SimpleNamespaceContext ctx = new SimpleNamespaceContext();
    ctx.addNamespace("a", "a");
    ctx.addNamespace("b", "b");

    Element a = xml.getDocumentElement();
    Element b = (Element) XMLUtil.getChildElementsByName(a, "B").get(0);
    Element c = (Element) XMLUtil.getChildElementsByName(b, "C").get(0);
    Element d1 = (Element) XMLUtil.getChildElementsByName(c, "D").get(0);
    Element d2 = (Element) XMLUtil.getChildElementsByName(c, "D").get(1);
    Element d3 = (Element) XMLUtil.getChildElementsByName(b, "D").get(0);
    Attr id = c.getAttributeNode("id");

    assertEquals("/a:A/b:B/a:C", XMLUtil.getXPathForElement(c, ctx));
    assertEquals("/a:A/b:B/a:C/@id", XMLUtil.getXPathForElement(id, ctx));
    assertEquals("/a:A/b:B/a:C/a:D[@name='testName']", XMLUtil.getXPathForElement(d1, ctx));
    assertEquals("/a:A/b:B/a:C/a:D[2]", XMLUtil.getXPathForElement(d2, ctx));
    assertEquals("/a:A/b:B/a:D", XMLUtil.getXPathForElement(d3, ctx));
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

public String getPropertyValue(Element element, String property) {
    String packages = null;/*  w ww.j av a2s  .  co m*/
    Node node = element.getAttributeNode(property);
    if (node == null) {
        List<Element> propertyElements = DomUtils.getChildrenByTagName(element, XmlConstants.PROPERTY);
        if (propertyElements != null) {
            for (Element childElement : propertyElements) {
                if (property.equals(childElement.getAttribute(XmlConstants.ATTRIBUTE_NAME))) {
                    packages = org.springframework.util.xml.DomUtils.getTextValue(childElement);
                    break;
                }
            }
        }
    } else {
        packages = node.getNodeValue();
    }
    return packages;
}

From source file:com.photon.maven.plugins.android.standalonemojos.ManifestUpdateMojo.java

public void updateManifest(File manifestFile) throws IOException, ParserConfigurationException, SAXException,
        TransformerException, MojoFailureException {
    Document doc = readManifest(manifestFile);

    Element manifestElement = doc.getDocumentElement();

    boolean dirty = false;

    if (StringUtils.isEmpty(parsedVersionName)) { // default to ${project.version}
        parsedVersionName = project.getVersion();
    }/*from w  w  w . j  a v  a  2s  .  c  om*/

    Attr versionNameAttrib = manifestElement.getAttributeNode(ATTR_VERSION_NAME);

    if (versionNameAttrib == null || !StringUtils.equals(parsedVersionName, versionNameAttrib.getValue())) {
        getLog().info("Setting " + ATTR_VERSION_NAME + " to " + parsedVersionName);
        manifestElement.setAttribute(ATTR_VERSION_NAME, parsedVersionName);
        dirty = true;
    }

    if ((parsedVersionCodeAutoIncrement && parsedVersionCode != null)
            || (parsedVersionCodeUpdateFromVersion && parsedVersionCode != null)
            || (parsedVersionCodeAutoIncrement && parsedVersionCodeUpdateFromVersion)) {
        throw new MojoFailureException("versionCodeAutoIncrement, versionCodeUpdateFromVersion and versionCode "
                + "are mutual exclusive. They cannot be specified at the same time. "
                + "Please specify either versionCodeAutoIncrement, versionCodeUpdateFromVersion or versionCode!");
    }

    if (parsedVersionCodeAutoIncrement) {
        Attr versionCode = manifestElement.getAttributeNode(ATTR_VERSION_CODE);
        int currentVersionCode = 0;
        if (versionCode != null) {
            currentVersionCode = NumberUtils.toInt(versionCode.getValue(), 0);
        }
        currentVersionCode++;
        manifestElement.setAttribute(ATTR_VERSION_CODE, String.valueOf(currentVersionCode));
        dirty = true;
    }

    if (parsedVersionCodeUpdateFromVersion) {
        String verString = project.getVersion();
        getLog().debug("Generating versionCode for " + verString);
        ArtifactVersion artifactVersion = new DefaultArtifactVersion(verString);
        String verCode = Integer.toString(artifactVersion.getMajorVersion())
                + Integer.toString(artifactVersion.getMinorVersion())
                + Integer.toString(artifactVersion.getIncrementalVersion());
        getLog().info("Setting " + ATTR_VERSION_CODE + " to " + verCode);
        manifestElement.setAttribute(ATTR_VERSION_CODE, verCode);
        dirty = true;
    }

    if (parsedVersionCode != null) {
        Attr versionCodeAttr = manifestElement.getAttributeNode(ATTR_VERSION_CODE);
        int currentVersionCode = 0;
        if (versionCodeAttr != null) {
            currentVersionCode = NumberUtils.toInt(versionCodeAttr.getValue(), 0);
        }
        if (currentVersionCode != parsedVersionCode) {
            getLog().info("Setting " + ATTR_VERSION_CODE + " to " + parsedVersionCode);
            manifestElement.setAttribute(ATTR_VERSION_CODE, String.valueOf(parsedVersionCode));
            dirty = true;
        }
    }

    if (!StringUtils.isEmpty(parsedSharedUserId)) {
        Attr sharedUserIdAttrib = manifestElement.getAttributeNode(ATTR_SHARED_USER_ID);

        if (sharedUserIdAttrib == null
                || !StringUtils.equals(parsedSharedUserId, sharedUserIdAttrib.getValue())) {
            getLog().info("Setting " + ATTR_SHARED_USER_ID + " to " + parsedSharedUserId);
            manifestElement.setAttribute(ATTR_SHARED_USER_ID, parsedSharedUserId);
            dirty = true;
        }
    }

    if (parsedDebuggable != null) {
        NodeList appElems = manifestElement.getElementsByTagName(ELEM_APPLICATION);

        // Update all application nodes. Not sure whether there will ever be more than one.
        for (int i = 0; i < appElems.getLength(); ++i) {
            Node node = appElems.item(i);
            getLog().info("Testing if node " + node.getNodeName() + " is application");
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                Attr debuggableAttrib = element.getAttributeNode(ATTR_DEBUGGABLE);
                if (debuggableAttrib == null
                        || parsedDebuggable != BooleanUtils.toBoolean(debuggableAttrib.getValue())) {
                    getLog().info("Setting " + ATTR_DEBUGGABLE + " to " + parsedDebuggable);
                    element.setAttribute(ATTR_DEBUGGABLE, String.valueOf(parsedDebuggable));
                    dirty = true;
                }
            }
        }
    }

    if (dirty) {
        if (!manifestFile.delete()) {
            getLog().warn("Could not remove old " + manifestFile);
        }
        getLog().info("Made changes to manifest file, updating " + manifestFile);
        writeManifest(manifestFile, doc);
    } else {
        getLog().info("No changes found to write to manifest file");
    }
}

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

/**
 * Update the root element property values with dynamic properties.
 * //  ww  w .  ja  v a2s . c  o  m
 * @param root Parent element
 * @param dynProps Dynamic property list
 */
protected void setProperties(Element root, DynPropertyList dynProps) {

    // Iterate all dynamic properties to update
    for (DynProperty dynProp : dynProps) {

        // Remove possible namespaces
        String xpath = removeNamespaces(dynProp.getKey());

        // If attr prefix present, there is an attribute else an element
        int index;
        if ((index = xpath.indexOf(XPATH_ARRAY_PREFIX + XPATH_ATTRIBUTE_PREFIX)) != -1) {

            // Set the new attribute value through container element
            Element elem = XmlUtils.findFirstElement(xpath.substring(0, index), root);
            if (elem == null) {

                logger.log(Level.WARNING, "Element " + xpath + " to set attribute value not exists on file");
            } else {

                String name = xpath.substring(index + 2, xpath.length() - 1);
                Attr attr = elem.getAttributeNode(name);
                if (attr == null) {

                    logger.log(Level.WARNING,
                            "Element attribute " + xpath + " to set value not exists on file");
                } else {

                    attr.setValue(dynProp.getValue());
                }
            }
        } else {

            // Set the new element content
            Element elem = XmlUtils.findFirstElement(xpath, root);

            if (elem == null) {

                logger.log(Level.WARNING, "Element " + xpath + " to set text content not exists on file");
            } else {

                elem.setTextContent(dynProp.getValue());
            }
        }
    }
}

From source file:be.fedict.eid.applet.service.signer.ooxml.RelationshipTransformService.java

public Data transform(Data data, XMLCryptoContext context) throws TransformException {
    LOG.debug("transform(data,context)");
    LOG.debug("data java type: " + data.getClass().getName());
    OctetStreamData octetStreamData = (OctetStreamData) data;
    LOG.debug("URI: " + octetStreamData.getURI());
    InputStream octetStream = octetStreamData.getOctetStream();
    Document relationshipsDocument;
    try {//from w w w  .ja va  2s  . c  o m
        relationshipsDocument = loadDocument(octetStream);
    } catch (Exception e) {
        throw new TransformException(e.getMessage(), e);
    }
    try {
        LOG.debug("relationships document: " + toString(relationshipsDocument));
    } catch (TransformerException e) {
        throw new TransformException(e.getMessage(), e);
    }
    Element nsElement = relationshipsDocument.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
            "http://schemas.openxmlformats.org/package/2006/relationships");
    Element relationshipsElement = relationshipsDocument.getDocumentElement();
    NodeList childNodes = relationshipsElement.getChildNodes();
    for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) {
        Node childNode = childNodes.item(nodeIdx);
        if (Node.ELEMENT_NODE != childNode.getNodeType()) {
            LOG.debug("removing node");
            relationshipsElement.removeChild(childNode);
            nodeIdx--;
            continue;
        }
        Element childElement = (Element) childNode;
        String idAttribute = childElement.getAttribute("Id");
        String typeAttribute = childElement.getAttribute("Type");
        LOG.debug("Relationship id attribute: " + idAttribute);
        LOG.debug("Relationship type attribute: " + typeAttribute);
        if (false == this.sourceIds.contains(idAttribute)
                && false == this.sourceTypes.contains(typeAttribute)) {
            LOG.debug("removing Relationship element: " + idAttribute);
            relationshipsElement.removeChild(childNode);
            nodeIdx--;
        }
        /*
         * See: ISO/IEC 29500-2:2008(E) - 13.2.4.24 Relationships Transform
         * Algorithm.
         */
        if (null == childElement.getAttributeNode("TargetMode")) {
            childElement.setAttribute("TargetMode", "Internal");
        }
    }
    LOG.debug("# Relationship elements: " + relationshipsElement.getElementsByTagName("*").getLength());
    sortRelationshipElements(relationshipsElement);
    try {
        return toOctetStreamData(relationshipsDocument);
    } catch (TransformerException e) {
        throw new TransformException(e.getMessage(), e);
    }
}

From source file:gov.nih.nci.cbiit.cmts.ws.servlet.AddNewScenario.java

/**
* Update the reference in .map to the .scs and .h3s files.
*
* @param  mapplingBakFileName  mapping file name
*///from   www . ja  v a  2s . c o m
public void updateMapping(String mapplingBakFileName, String fileHome) throws Exception {

    Document xmlDOM = readFile(mapplingBakFileName);
    NodeList components = xmlDOM.getElementsByTagName("component");
    for (int i = 0; i < components.getLength(); i++) {
        Element component = (Element) components.item(i);
        //update location of SCS, H3S
        Attr locationAttr = component.getAttributeNode("location");
        Attr typeAttr = component.getAttributeNode("type");

        if (locationAttr != null) {
            String cmpType = "";
            if (typeAttr != null)
                cmpType = typeAttr.getValue();
            if (cmpType != null && cmpType.equalsIgnoreCase("v2"))
                continue;
            String originalLoc = locationAttr.getValue();
            String localName = extractOriginalFileName(originalLoc);
            //                locationAttr.setValue(fileHome+File.separator+cmpType+File.separator+localName);

            //includedXSDList.add(cmpType+File.separator+localName.toLowerCase());
            if (cmpType.equalsIgnoreCase(SOURCE_DIRECTORY_TAG)) {
                sourceOriginalXSDPath = originalLoc;
                locationAttr.setValue(SOURCE_DIRECTORY_TAG + File.separator + localName.toLowerCase());
                includedXSDList.add(SOURCE_DIRECTORY_TAG + File.separator + localName.toLowerCase());
            }
            if (cmpType.equalsIgnoreCase(TARGET_DIRECTORY_TAG)) {
                targetOriginalXSDPath = originalLoc;
                locationAttr.setValue(TARGET_DIRECTORY_TAG + File.separator + localName.toLowerCase());
                includedXSDList.add(TARGET_DIRECTORY_TAG + File.separator + localName.toLowerCase());
            }
            //System.out.println("CCCCC updateMapping Add file list : " + cmpType+File.separator+localName.toLowerCase());
            //locationAttr.setValue(cmpType+File.separator+localName);
        }
        //             //update VOM reference
        //             Attr groupAttr = component.getAttributeNode("group");
        //             if (groupAttr!=null
        //                   &&groupAttr.getValue()!=null
        //                   &&groupAttr.getValue().equalsIgnoreCase("vocabulary"))
        //             {
        //                NodeList chldComps = component.getElementsByTagName("data");
        //                for(int j=0;j<chldComps.getLength();j++)
        //                {
        //                   Element chldElement = (Element)chldComps.item(j);
        //                   Attr valueAttr=chldElement.getAttributeNode("value");
        //                   if (valueAttr!=null)
        //                   {
        //                      String localFileName=extractOriginalFileName(valueAttr.getValue());
        //                      valueAttr.setValue(localFileName);
        //                   }
        //                }
        //             }
    }
    System.out.println("AddNewScenario.updateMapping()..mapbakfile:" + mapplingBakFileName);

    outputXML(xmlDOM, mapplingBakFileName.substring(0, mapplingBakFileName.lastIndexOf(".bak")));
}