Example usage for org.dom4j Node getNodeType

List of usage examples for org.dom4j Node getNodeType

Introduction

In this page you can find the example usage for org.dom4j Node getNodeType.

Prototype

short getNodeType();

Source Link

Document

Returns the code according to the type of node.

Usage

From source file:org.danann.cernunnos.xml.PrependNodeTask.java

License:Apache License

@SuppressWarnings("unchecked")
public void perform(TaskRequest req, TaskResponse res) {

    // Figure out where to put the content...
    Branch p = null;/*from   w  w w  . j  av a  2s. c o  m*/
    int index;
    if (sibling != null) {
        Node sib = (Node) sibling.evaluate(req, res);
        p = sib.getParent();
        index = p.indexOf(sib);
    } else {
        // Work from the PARENT...
        p = (Branch) parent.evaluate(req, res);
        index = 0;
    }

    // Figure out what content to add...
    List list = null;
    if (content != null && content.size() > 0) {
        list = content;
    } else {
        list = new LinkedList();
        list.add(node.evaluate(req, res));
    }

    // Evaluate phrases & add...
    for (Object o : list) {

        Node n = (Node) ((Node) o).clone();
        NodeProcessor.evaluatePhrases(n, grammar, req, res);

        // If the parent is an element, check if we should
        // carry the parent namespace over to the child...
        if ((Boolean) apply_namespace.evaluate(req, res) && p.getNodeType() == Node.ELEMENT_NODE
                && !((Element) p).getNamespace().equals(Namespace.NO_NAMESPACE)) {
            // We know the parent is an Element w/ a namespace,
            // is the child (also) an Element w/ none?
            if (n.getNodeType() == Node.ELEMENT_NODE
                    && ((Element) n).getNamespace().equals(Namespace.NO_NAMESPACE)) {
                // Yes -- we need to port the namespace forward...
                Namespace nsp = ((Element) p).getNamespace();
                if (log.isTraceEnabled()) {
                    StringBuffer msg = new StringBuffer();
                    msg.append("Adding the following namespace to <").append(n.getName()).append(">:  ")
                            .append(nsp);
                    log.trace(msg.toString());
                }
                NodeProcessor.applyNamespace(nsp, (Element) n);
            }
        }

        // Although they *are* nodes, attributes are not technically
        // content, and therefore they must have special treatment...
        if (p.getNodeType() == Node.ELEMENT_NODE && n.getNodeType() == Node.ATTRIBUTE_NODE) {
            // Add attributes by calling addAttribute on the Element contract...
            ((Element) p).add((Attribute) n);
        } else {
            // Add everything else as 'content'...
            p.content().add(index++, n);
        }

    }

}

From source file:org.dommons.dom.dom4j.XDom4jNode.java

License:Open Source License

/**
 * ??//  ww w. j  a  v a  2  s.co m
 * @param parent 
 * @param name ???
 * @return 
 */
private static Element element(Branch parent, String name) {
    for (Iterator<Node> it = parent.nodeIterator(); it.hasNext();) {
        Node node = it.next();
        if (node.getNodeType() == Node.ELEMENT_NODE && name.equals(node.getName()))
            return (Element) node;
    }
    return null;
}

From source file:org.dommons.dom.dom4j.XDom4jNode.java

License:Open Source License

public List<XElement> elements() {
    List<XElement> list = new ArrayList();
    for (Iterator<Node> it = target().nodeIterator(); it.hasNext();) {
        Node node = it.next();
        if (node.getNodeType() == Node.ELEMENT_NODE)
            list.add(new XDom4jElement((Element) node));
    }//from  w ww . j av  a  2s.c o m
    return list;
}

From source file:org.dommons.dom.dom4j.XDom4jNode.java

License:Open Source License

public List<XElement> elements(String... names) {
    Branch ele = element(names, 0, -1);/*from  ww w .  j  a  va 2s  . c  o m*/
    List<XElement> list = new ArrayList();
    if (ele != null) {
        for (Iterator<Node> it = ele.nodeIterator(); it.hasNext();) {
            Node node = it.next();
            if (node.getNodeType() == Node.ELEMENT_NODE && names[names.length - 1].equals(node.getName()))
                list.add(new XDom4jElement((Element) node));
        }
    }
    return list;
}

From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java

License:Apache License

private void removeNamespaces(Element elem) {
    elem.setQName(QName.get(elem.getName(), Namespace.NO_NAMESPACE, elem.getQualifiedName()));
    Node n = null;
    for (int i = 0; i < elem.content().size(); i++) {
        n = (Node) elem.content().get(i);
        if (n.getNodeType() == Node.ATTRIBUTE_NODE)
            ((Attribute) n).setNamespace(Namespace.NO_NAMESPACE);
        if (n.getNodeType() == Node.ELEMENT_NODE)
            removeNamespaces((Element) n);
    }//from  w w  w.jav  a 2s.c  o m
}

From source file:org.foxbpm.bpmn.converter.util.BpmnXMLUtil.java

License:Apache License

/**
 * ??/* w  w  w .j  a  v a2  s . co  m*/
 * 
 * @param element
 *            ?
 * @return ?
 */
@SuppressWarnings("rawtypes")
public static String parseExpression(Element element) {
    Node node = null;
    if (element == null) {
        return null;
    }
    for (Iterator iterator = element.nodeIterator(); iterator.hasNext();) {
        node = (Node) iterator.next();
        if (Element.CDATA_SECTION_NODE == node.getNodeType()) {
            return node.getText();
        }
    }
    return null;
}

From source file:org.hudsonci.xpath.impl.Dom2Dom.java

License:Open Source License

private org.w3c.dom.Node createChild(Node child, org.w3c.dom.Node wparent) {
    int type = child.getNodeType();

    // Collapse multiple consecutive text nodes to a single text node
    // with trimmed value.
    if (type != Node.TEXT_NODE)
        endText(wparent);/*from  www.  j a va2s . c  o m*/

    Name name;
    org.w3c.dom.Node node = null;

    switch (type) {
    case Node.ATTRIBUTE_NODE:
        break;
    case Node.CDATA_SECTION_NODE:
        CDATA cd = (CDATA) child;
        wparent.appendChild(node = wdoc.createCDATASection(cd.getText()));
        break;
    case Node.COMMENT_NODE:
        Comment co = (Comment) child;
        wparent.appendChild(node = wdoc.createComment(co.getText()));
        break;
    case Node.DOCUMENT_TYPE_NODE:
        DocumentType dt = (DocumentType) child;
        wparent.appendChild(new XDocumentType(dt, wparent));
        break;
    case Node.ELEMENT_NODE:
        Element el = (Element) child;
        name = new Name(el);
        org.w3c.dom.Element e = name.namespaceURI == null ? wdoc.createElement(name.qualifiedName)
                : wdoc.createElementNS(name.namespaceURI, name.qualifiedName);
        wparent.appendChild(e);
        node = currentElement = e;

        for (int i = 0, n = el.attributeCount(); i < n; i++) {
            Attribute at = el.attribute(i);
            name = new Name(at);
            if (name.namespaceURI == null)
                e.setAttribute(name.qualifiedName, at.getValue());
            else
                e.setAttributeNS(name.namespaceURI, name.qualifiedName, at.getValue());
        }
        return e;
    case Node.ENTITY_REFERENCE_NODE:
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        ProcessingInstruction p = (ProcessingInstruction) child;
        wparent.appendChild(node = wdoc.createProcessingInstruction(p.getTarget(), p.getText()));
        break;
    case Node.TEXT_NODE:
        textBuilder.append(child.getText());
        lastText = (Text) child;
        break;
    case Node.NAMESPACE_NODE:
        Namespace ns = (Namespace) child;
        name = new Name(ns);
        currentElement.setAttribute(name.qualifiedName, ns.getURI());
        break;
    default:
        throw new IllegalStateException("Unknown node type");
    }
    if (node != null)
        reverseMap.put(node, child);
    return null;
}

From source file:org.jasig.portal.io.xml.SpELDataTemplatingStrategy.java

License:Apache License

@Override
public Source processTemplates(Document data, String filename) {

    log.trace("Processing templates for document XML={}", data.asXML());
    for (String xpath : XPATH_EXPRESSIONS) {
        @SuppressWarnings("unchecked")
        List<Node> nodes = data.selectNodes(xpath);
        for (Node n : nodes) {
            String inpt, otpt;/*from  w  w w. j  a v  a 2s . c  o  m*/
            switch (n.getNodeType()) {
            case org.w3c.dom.Node.ATTRIBUTE_NODE:
                Attribute a = (Attribute) n;
                inpt = a.getValue();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    a.setValue(otpt);
                }
                break;
            case org.w3c.dom.Node.TEXT_NODE:
            case org.w3c.dom.Node.CDATA_SECTION_NODE:
                inpt = n.getText();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    n.setText(otpt);
                }
                break;
            default:
                String msg = "Unsupported node type:  " + n.getNodeTypeName();
                throw new RuntimeException(msg);
            }
        }
    }

    final SAXSource rslt = new DocumentSource(data);
    rslt.setSystemId(filename); // must be set, else import chokes
    return rslt;

}

From source file:org.jasig.portal.tenants.TemplateDataTenantOperationsListener.java

License:Apache License

@Override
public void onCreate(final ITenant tenant) {

    final StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setRootObject(new RootObjectImpl(tenant));

    /*/*from   w  ww .  j  a v  a  2  s .co m*/
     * First load dom4j Documents and sort the entity files into the proper order 
     */
    final Map<PortalDataKey, Set<Document>> importQueue = new HashMap<PortalDataKey, Set<Document>>();
    Resource rsc = null;
    try {
        for (Resource r : templateResources) {
            rsc = r;
            if (log.isDebugEnabled()) {
                log.debug("Loading template resource file for tenant " + "'" + tenant.getFname() + "':  "
                        + rsc.getFilename());
            }
            final Document doc = reader.read(rsc.getInputStream());
            final QName qname = doc.getRootElement().getQName();
            PortalDataKey atLeastOneMatchingDataKey = null;
            for (PortalDataKey pdk : dataKeyImportOrder) {
                // Matching is tougher because it's dom4j <> w3c...
                boolean matches = qname.getName().equals(pdk.getName().getLocalPart())
                        && qname.getNamespaceURI().equals(pdk.getName().getNamespaceURI());
                if (matches) {
                    // Found the right bucket...
                    atLeastOneMatchingDataKey = pdk;
                    Set<Document> bucket = importQueue.get(atLeastOneMatchingDataKey);
                    if (bucket == null) {
                        // First of these we've seen;  create the bucket;
                        bucket = new HashSet<Document>();
                        importQueue.put(atLeastOneMatchingDataKey, bucket);
                    }
                    bucket.add(doc);
                    /*
                     * At this point, we would normally add a break;
                     * statement, but group_membership.xml files need to
                     * match more than one PortalDataKey.
                     */
                }
            }
            if (atLeastOneMatchingDataKey == null) {
                // We can't proceed
                throw new RuntimeException(
                        "No PortalDataKey found for QName:  " + doc.getRootElement().getQName());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to process the specified template:  " + (rsc != null ? rsc.getFilename() : ""), e);
    }

    log.trace("Ready to import data entity templates for new tenant '{}';  importQueue={}", tenant.getName(),
            importQueue);

    /*
     * Now import the identified entities each bucket in turn 
     */
    Document doc = null;
    org.w3c.dom.Document w3c = null;
    try {
        for (PortalDataKey pdk : dataKeyImportOrder) {
            Set<Document> bucket = importQueue.get(pdk);
            if (bucket != null) {
                log.debug("Importing the specified PortalDataKey tenant '{}':  {}", tenant.getName(),
                        pdk.getName());
                for (Document d : bucket) {
                    doc = d;
                    log.trace("Importing document XML={}", doc.asXML());
                    for (String xpath : XPATH_EXPRESSIONS) {
                        @SuppressWarnings("unchecked")
                        List<Node> nodes = doc.selectNodes(xpath);
                        for (Node n : nodes) {
                            String inpt, otpt;
                            switch (n.getNodeType()) {
                            case org.w3c.dom.Node.ATTRIBUTE_NODE:
                                Attribute a = (Attribute) n;
                                inpt = a.getValue();
                                otpt = processText(inpt, ctx);
                                if (!otpt.equals(inpt)) {
                                    a.setValue(otpt);
                                }
                                break;
                            case org.w3c.dom.Node.TEXT_NODE:
                                Text t = (Text) n;
                                inpt = t.getText();
                                otpt = processText(inpt, ctx);
                                if (!otpt.equals(inpt)) {
                                    t.setText(otpt);
                                }
                                break;
                            default:
                                String msg = "Unsupported node type:  " + n.getNodeTypeName();
                                throw new RuntimeException(msg);
                            }
                        }
                    }
                    w3c = writer.write(doc, domImpl);
                    Source source = new DOMSource(w3c);
                    source.setSystemId(rsc.getFilename()); // must be set, else import chokes
                    dataHandlerService.importData(source, pdk);
                }
            }
        }

    } catch (Exception e) {
        log.warn("w3c DOM=" + this.nodeToString(w3c));
        throw new RuntimeException(
                "Failed to process the specified template document:  " + (doc != null ? doc.asXML() : ""), e);
    }

}

From source file:org.olat.ims.qti.qpool.QTIExportProcessor.java

License:Apache License

/**
 * Collect the file and rewrite the //from  www.  j  a  v  a2  s  .com
 * @param el
 * @param container
 * @param materials
 * @param paths
 */
private void collectResourcesInMatText(Element el, VFSContainer container, ItemsAndMaterials materials) {
    //mattext
    @SuppressWarnings("unchecked")
    List<Element> mattextList = el.selectNodes(".//mattext");
    for (Element mat : mattextList) {
        Attribute texttypeAttr = mat.attribute("texttype");
        String texttype = texttypeAttr.getValue();
        if ("text/html".equals(texttype)) {
            @SuppressWarnings("unchecked")
            List<Node> childElList = new ArrayList<Node>(mat.content());
            for (Node childEl : childElList) {
                mat.remove(childEl);
            }

            for (Node childEl : childElList) {
                if (Node.CDATA_SECTION_NODE == childEl.getNodeType()) {
                    CDATA data = (CDATA) childEl;
                    boolean changed = false;
                    String text = data.getText();
                    List<String> materialPaths = findMaterialInMatText(text);
                    for (String materialPath : materialPaths) {
                        VFSItem matVfsItem = container.resolve(materialPath);
                        if (matVfsItem instanceof VFSLeaf) {
                            String exportUri = generateExportPath(materials.getPaths(), matVfsItem);
                            materials.addMaterial(new ItemMaterial((VFSLeaf) matVfsItem, exportUri));
                            text = text.replaceAll(materialPath, exportUri);
                            changed = true;
                        }
                    }
                    if (changed) {
                        mat.addCDATA(text);
                    } else {
                        mat.add(childEl);
                    }
                } else {
                    mat.add(childEl);
                }
            }
        }
    }
}