Example usage for org.w3c.dom Node removeChild

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

Introduction

In this page you can find the example usage for org.w3c.dom Node 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:org.openmrs.module.metadatasharing.converter.ConceptMap19Converter.java

@Override
public void convert(Document doc, Version fromVersion, Version toVersion, ConverterContext context)
        throws SerializationException {
    if (fromVersion.compareTo(new Version("1.9")) >= 0 || toVersion.compareTo(new Version("1.9")) < 0) {
        return;//from  w w w.j  av a 2s .  c  om
    }

    Map<String, Element> mapTypeElements = new HashMap<String, Element>();

    NodeList maps = doc.getElementsByTagName("org.openmrs.ConceptMap");
    for (int i = 0; i < maps.getLength(); i++) {
        Node map = maps.item(i);

        Element commentElement = getChildElement(map, "comment");
        if (commentElement == null) {
            continue;
        }

        map.removeChild(commentElement);

        String mapTypeName = getMapTypeName(commentElement);

        if (mapTypeName == null) {
            continue;
        }

        Element mapTypeElement = mapTypeElements.get(mapTypeName);

        if (mapTypeElement == null) {
            ConceptMapType mapType = Context.getConceptService().getConceptMapTypeByName(mapTypeName);

            if (mapType == null) {
                continue;
            }

            mapTypeElement = newElement(doc, "conceptMapType", mapType, context);
            mapTypeElements.put(mapTypeName, mapTypeElement);

            map.appendChild(mapTypeElement);
        } else {
            Element reference = doc.createElement("conceptMapTye");
            newReferenced(reference, mapTypeElement);
            map.appendChild(reference);
        }
    }

    Map<String, Element> referenceTermElements = new HashMap<String, Element>();

    for (int i = 0; i < maps.getLength(); i++) {
        Node map = maps.item(i);
        Element source = getChildElement(map, "source");
        map.removeChild(source);
        Element referencedSource = (Element) reference(source, context);

        Element sourceCode = getChildElement(map, "sourceCode");
        map.removeChild(sourceCode);

        //ConceptReferenceTerms are the same if source and sourceCode are the same
        String key = referencedSource.getAttribute("uuid") + sourceCode.getTextContent();

        Element referenceTermElement = referenceTermElements.get(key);

        if (referenceTermElement == null) {
            ConceptReferenceTerm referenceTerm = new ConceptReferenceTerm();
            String uuid = UUID.nameUUIDFromBytes(((Element) map).getAttribute("uuid").getBytes()).toString();
            referenceTerm.setUuid(uuid);
            referenceTerm.setCode(sourceCode.getTextContent());
            referenceTermElement = newElement(doc, "conceptReferenceTerm", referenceTerm, context);
            source = (Element) source.cloneNode(true);
            source = (Element) doc.renameNode(source, "", "conceptSource");
            referenceTermElement.appendChild(source);

            referenceTermElements.put(key, referenceTermElement);
            map.appendChild(referenceTermElement);
        } else {
            Element reference = doc.createElement("conceptReferenceTerm");
            newReferenced(reference, referenceTermElement);
            map.appendChild(reference);
        }
    }
}

From source file:org.openmrs.module.metadatasharing.converter.ConceptMapConverter.java

/**
 * @see org.openmrs.module.metadatasharing.converter.BaseConverter#convert(org.w3c.dom.Document, org.openmrs.module.metadatasharing.util.Version, org.openmrs.module.metadatasharing.util.Version, org.openmrs.module.metadatasharing.converter.BaseConverter.ConverterContext)
 * @should replace source if the from version is pre one nine
 * @should replace nothing if the to version is post one nine
 *///from w  w  w .  j a v  a  2 s. co  m
@Override
public void convert(Document doc, Version fromVersion, Version toVersion, ConverterContext context)
        throws SerializationException {
    if (fromVersion.compareTo(new Version("1.9")) >= 0 || toVersion.compareTo(new Version("1.9")) < 0) {
        return;
    }

    Map<String, Element> mapTypeElements = new HashMap<String, Element>();

    NodeList maps = doc.getElementsByTagName("org.openmrs.ConceptMap");
    for (int i = 0; i < maps.getLength(); i++) {
        Node map = maps.item(i);

        Element commentElement = getChildElement(map, "comment");
        if (commentElement == null) {
            continue;
        }

        map.removeChild(commentElement);

        String mapTypeName = getMapTypeName(commentElement);

        if (mapTypeName == null) {
            continue;
        }

        Element mapTypeElement = mapTypeElements.get(mapTypeName);

        if (mapTypeElement == null) {
            ConceptMapType mapType = Context.getConceptService().getConceptMapTypeByName(mapTypeName);

            if (mapType == null) {
                continue;
            }

            mapTypeElement = newElement(doc, "conceptMapType", mapType, context);
            mapTypeElements.put(mapTypeName, mapTypeElement);

            map.appendChild(mapTypeElement);
        } else {
            Element reference = doc.createElement("conceptMapTye");
            newReferenced(reference, mapTypeElement);
            map.appendChild(reference);
        }
    }

    Map<String, Element> referenceTermElements = new HashMap<String, Element>();

    for (int i = 0; i < maps.getLength(); i++) {
        Node map = maps.item(i);
        Element source = getChildElement(map, "source");
        map.removeChild(source);
        Element referencedSource = (Element) reference(source, context);

        Element sourceCode = getChildElement(map, "sourceCode");
        map.removeChild(sourceCode);

        //ConceptReferenceTerms are the same if source and sourceCode are the same
        String key = referencedSource.getAttribute("uuid") + sourceCode.getTextContent();

        Element referenceTermElement = referenceTermElements.get(key);

        if (referenceTermElement == null) {
            ConceptReferenceTerm referenceTerm = new ConceptReferenceTerm();
            String uuid = UUID.nameUUIDFromBytes(((Element) map).getAttribute("uuid").getBytes()).toString();
            referenceTerm.setUuid(uuid);
            referenceTerm.setCode(sourceCode.getTextContent());
            referenceTermElement = newElement(doc, "conceptReferenceTerm", referenceTerm, context);
            source = (Element) source.cloneNode(true);
            source = (Element) doc.renameNode(source, "", "conceptSource");
            referenceTermElement.appendChild(source);

            referenceTermElements.put(key, referenceTermElement);
            map.appendChild(referenceTermElement);
        } else {
            Element reference = doc.createElement("conceptReferenceTerm");
            newReferenced(reference, referenceTermElement);
            map.appendChild(reference);
        }
    }
}

From source file:org.opensingular.internal.lib.commons.xml.MElement.java

/**
 * Atualiza o Node (Element ou atributo) j exisitente. Se o Node no for
 * localizado, ento adiciona se o valor for diferente de null.
 *
 * @param xPath Caminho do Node a ser atualizado ou criado
 * @param value Novo valor do Node. Se for null, ento o valor  limpo. Se o
 *              element j existir e valor for null, ento transforma a tag em
 *              empty, mas a mantm no XML.
 * @return O Node alterado ou criado, ou null se no for possvel atualizar
 * o valor do mesmo./*from  ww w .j  a v  a2 s .c o  m*/
 */
public final Node updateNode(String xPath, String value) {
    Node n = getNode(xPath);
    if ((n == null) && !StringUtils.isEmpty(value)) {
        return addElement(xPath, value);
    } else if (n instanceof Element) {
        Node filho = n.getFirstChild();
        if (filho == null) {
            if (!StringUtils.isEmpty(value)) {
                Document d = n.getOwnerDocument();
                Text txt = d.createTextNode(value);
                n.appendChild(txt);
            }
        } else if (XmlUtil.isNodeTypeText(filho)) {
            if (!StringUtils.isEmpty(value)) {
                filho.setNodeValue(value);
            } else {
                n.removeChild(filho);
            }
        } else {
            return null;
        }
    } else if (n instanceof Attr) {
        //No h como saber quem  o pai (n.getParentNode() retorna null)
        if (value == null) {
            return addElement(xPath, ""); //Fora a remoo do atributo
        }
        return addElement(xPath, value);
    } else {
        return null;
    }
    return n;
}

From source file:org.pentaho.di.trans.steps.xmlinput.XMLInput.java

private Object[] getRowFromXML() throws KettleValueException {
    // finished reading the file, read the next file

    while (data.itemPosition >= data.itemCount || data.file == null) {
        data.file = null;/*from   ww  w  . ja  va2s .co m*/
        if (!openNextFile()) {
            return null;
        }
    }

    Object[] outputRowData = buildEmptyRow();

    // Get the item in the XML file...

    // First get the appropriate node

    Node itemNode;
    if (meta.getInputPosition().length > 1) {
        itemNode = XMLHandler.getSubNodeByNr(data.section, data.itemElement, data.itemPosition);
    } else {
        itemNode = data.section; // Only the root node, 1 element to read
        // in the whole document.
    }
    data.itemPosition++;

    // Read from the Node...
    for (int i = 0; i < meta.getInputFields().length; i++) {
        Node node = itemNode;

        XMLInputField xmlInputField = meta.getInputFields()[i];

        // This value will contain the value we're looking for...
        //
        String value = null;

        for (int p = 0; (value == null) && node != null && p < xmlInputField.getFieldPosition().length; p++) {
            XMLInputFieldPosition pos = xmlInputField.getFieldPosition()[p];

            switch (pos.getType()) {
            case XMLInputFieldPosition.XML_ELEMENT: {
                if (pos.getElementNr() <= 1) {
                    Node subNode = XMLHandler.getSubNode(node, pos.getName());
                    if (subNode != null) {
                        if (p == xmlInputField.getFieldPosition().length - 1) // last
                        // level
                        {
                            value = XMLHandler.getNodeValue(subNode);
                        }
                    } else {
                        if (log.isDebug())
                            logDebug(BaseMessages.getString(PKG, "XMLInput.Log.UnableToFindPosition",
                                    pos.toString(), node.toString()));
                    }
                    node = subNode;
                } else
                // Multiple possible values: get number
                // pos.getElementNr()!
                {
                    Node subNode = XMLHandler.getSubNodeByNr(node, pos.getName(), pos.getElementNr() - 1,
                            false);
                    if (subNode != null) {
                        if (p == xmlInputField.getFieldPosition().length - 1) // last
                        // level
                        {
                            value = XMLHandler.getNodeValue(subNode);
                        }
                    } else {
                        if (log.isDebug())
                            logDebug(BaseMessages.getString(PKG, "XMLInput.Log.UnableToFindPosition",
                                    pos.toString(), node.toString()));
                    }
                    node = subNode;
                }
            }
                break;

            case XMLInputFieldPosition.XML_ATTRIBUTE: {
                value = XMLHandler.getTagAttribute(node, pos.getName());
            }
                break;
            case XMLInputFieldPosition.XML_ROOT: {
                value = XMLHandler.getNodeValue(node);
            }
                break;
            default:
                break;
            }

        }

        // OK, we have grabbed the string called value
        // Trim it, convert it, ...

        // DO Trimming!
        switch (xmlInputField.getTrimType()) {
        case XMLInputField.TYPE_TRIM_LEFT:
            value = Const.ltrim(value);
            break;
        case XMLInputField.TYPE_TRIM_RIGHT:
            value = Const.rtrim(value);
            break;
        case XMLInputField.TYPE_TRIM_BOTH:
            value = Const.trim(value);
            break;
        default:
            break;
        }

        // System.out.println("after trim, field #"+i+" : "+v);

        // DO CONVERSIONS...
        //
        ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta(i);
        ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(i);
        outputRowData[i] = targetValueMeta.convertData(sourceValueMeta, value);

        // Do we need to repeat this field if it is null?
        if (meta.getInputFields()[i].isRepeated()) {
            if (data.previousRow != null && Const.isEmpty(value)) {
                outputRowData[i] = data.previousRow[i];
            }
        }
    } // End of loop over fields...

    int outputIndex = meta.getInputFields().length;

    // See if we need to add the filename to the row...
    if (meta.includeFilename() && !Const.isEmpty(meta.getFilenameField())) {
        outputRowData[outputIndex++] = KettleVFS.getFilename(data.file);
    }

    // See if we need to add the row number to the row...
    if (meta.includeRowNumber() && !Const.isEmpty(meta.getRowNumberField())) {
        outputRowData[outputIndex++] = new Long(data.rownr);
    }

    RowMetaInterface irow = getInputRowMeta();

    data.previousRow = irow == null ? outputRowData : (Object[]) irow.cloneRow(outputRowData); // copy it to make
    // surely the next step doesn't change it in between...
    data.rownr++;

    // Throw away the information in the item?
    NodeList nodeList = itemNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        itemNode.removeChild(nodeList.item(i));
    }

    return outputRowData;
}

From source file:org.regenstrief.util.XMLUtil.java

/**
 * Strips whitespace from a Node tree/* w  w  w  .  j a v a2s  .c  o  m*/
 * 
 * @param n the root Node
 **/
public final static void stripWhitespace(final Node n) {
    if (n == null) {
        return;
    } else if (n.getNodeType() == Node.TEXT_NODE) {
        final Node p = canStripTextWhitespace(n);
        if (p != null) {
            p.removeChild(n);
        }
    } else {
        final NodeList list = n.getChildNodes();
        for (int i = size(list) - 1; i >= 0; i--) {
            stripWhitespace(list.item(i));
        }
    }
}

From source file:org.regenstrief.util.XMLUtil.java

private final static boolean expandFragments(final Node parent, final Node ref, final Node frag) {
    if (frag instanceof DocumentFragment) {
        for (final Node child : new NodeArrayList(frag.getChildNodes())) { // Copy since we'll be modifying it
            if (!expandFragments(parent, ref, child)) {
                parent.insertBefore(child, ref);
            }/*from ww  w .j  ava2  s .com*/
        }
        parent.removeChild(frag);
        return true;
    }

    return false;
}

From source file:org.sakaiproject.tool.assessment.qti.util.XmlStringBuffer.java

/**
 * remove element// w w w. java2 s . c o m
 *
 * @param xpath
 */
public final void removeElement(String xpath) {
    if (log.isDebugEnabled()) {
        log.debug("removeElement(String " + xpath + ")");
    }

    List nodes = this.selectNodes(xpath);
    Iterator iterator = nodes.iterator();
    while (iterator.hasNext()) {
        Node node = (Node) iterator.next();
        Node parent = node.getParentNode();
        parent.removeChild(node);
    }
}

From source file:org.silverpeas.SilverpeasSettings.xml.transform.XPathTransformer.java

/**
 * Transform the DOM tree using the configuration.
 * @param configuration the transformation configuration.
 * @param doc the DOM tree to be updated.
 *//*from   w  w  w  . ja  v  a2s.  c  o  m*/
protected void applyTransformation(XmlConfiguration configuration, Document doc) {
    List<Parameter> parameters = configuration.getParameters();
    for (Parameter parameter : parameters) {
        displayMessageln("\t" + parameter.getKey() + " (mode:" + parameter.getMode() + ")");
        Node rootXpathNode = getMatchingNode(parameter.getKey(), doc);
        if (rootXpathNode != null) {
            for (Value value : parameter.getValues()) {
                switch (value.getMode()) {
                case XmlTreeHandler.MODE_INSERT: {
                    createNewNode(doc, rootXpathNode, value);
                }
                    break;
                case XmlTreeHandler.MODE_DELETE: {
                    Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    rootXpathNode.removeChild(deletedNode);
                }
                    break;
                case XmlTreeHandler.MODE_UPDATE: {
                    Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    if (oldNode == null) {
                        createNewNode(doc, rootXpathNode, value);
                    } else {
                        if (rootXpathNode.equals(oldNode)) {
                            rootXpathNode = rootXpathNode.getParentNode();
                        }
                        Node newNode = oldNode.cloneNode(true);
                        if (oldNode instanceof Element) {
                            ((Element) newNode).setTextContent(value.getValue());
                            rootXpathNode.replaceChild(newNode, oldNode);
                        } else {
                            ((Attr) newNode).setValue(value.getValue());
                            rootXpathNode.getAttributes().setNamedItem(newNode);
                        }

                    }
                    break;
                }
                }
            }
        }
    }
}

From source file:org.silverpeas.util.xml.transform.XPathTransformer.java

/**
 * Transform the DOM tree using the configuration.
 *
 * @param configuration the transformation configuration.
 * @param doc the DOM tree to be updated.
 */// w w w .j  a v a  2 s  . co m
protected void applyTransformation(XmlConfiguration configuration, Document doc) {
    List<Parameter> parameters = configuration.getParameters();
    for (Parameter parameter : parameters) {
        console.printMessage('\t' + parameter.getKey() + " (mode:" + parameter.getMode() + ')');
        Node rootXpathNode = getMatchingNode(parameter.getKey(), doc);
        if (rootXpathNode != null) {
            for (Value value : parameter.getValues()) {
                switch (value.getMode()) {
                case XmlTreeHandler.MODE_INSERT: {
                    createNewNode(doc, rootXpathNode, value);
                }
                    break;
                case XmlTreeHandler.MODE_DELETE: {
                    Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    rootXpathNode.removeChild(deletedNode);
                }
                    break;
                case XmlTreeHandler.MODE_UPDATE: {
                    Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    if (oldNode == null) {
                        createNewNode(doc, rootXpathNode, value);
                    } else {
                        if (rootXpathNode.equals(oldNode)) {
                            rootXpathNode = rootXpathNode.getParentNode();
                        }
                        Node newNode = oldNode.cloneNode(true);
                        if (oldNode instanceof Element) {
                            newNode.setTextContent(value.getValue());
                            rootXpathNode.replaceChild(newNode, oldNode);
                        } else {
                            ((Attr) newNode).setValue(value.getValue());
                            rootXpathNode.getAttributes().setNamedItem(newNode);
                        }

                    }
                    break;
                }
                }
            }
        }
    }
}

From source file:org.smartfrog.avalanche.client.sf.apps.gt4.javawscore.utils.EditXML.java

public void removeNode(Element ele) {
    Node parent = ele.getParentNode();
    parent.removeChild(ele);
}