Example usage for org.dom4j Element nodeCount

List of usage examples for org.dom4j Element nodeCount

Introduction

In this page you can find the example usage for org.dom4j Element nodeCount.

Prototype

int nodeCount();

Source Link

Document

Returns the number of Node instances that this branch contains.

Usage

From source file:no.met.jtimeseries.parser.OceanForecastParseScheme.java

License:Open Source License

public void xmlTreeWalk(Element element) throws ParseException {
    for (int i = 0, size = element.nodeCount(); i < size; i++) {
        Node node = element.node(i);
        if (node instanceof Element) {
            if (((Element) node).getName().equals("begin")) {
                timeFrom = dateFormat.parse(node.getText());
            }//from  ww w  .  j a va2 s.  c o m
            // read phenomena if it is inside forecast-period
            else if (forecastPeriod.inside(timeFrom))
                readPhenomenen((Element) node);
            xmlTreeWalk((Element) node);
        }
    }
}

From source file:org.craftercms.studio.impl.v1.service.site.SiteServiceImpl.java

License:Open Source License

private Map<String, Object> createMap(Element element) {
    Map<String, Object> map = new HashMap<String, Object>();
    for (int i = 0, size = element.nodeCount(); i < size; i++) {
        Node currentNode = element.node(i);
        if (currentNode instanceof Element) {
            Element currentElement = (Element) currentNode;
            String key = currentElement.getName();
            Object toAdd = null;/*  ww w.  ja  v a  2 s. c o m*/
            if (currentElement.isTextOnly()) {
                toAdd = currentElement.getStringValue();
            } else {
                toAdd = createMap(currentElement);
            }
            if (map.containsKey(key)) {
                Object value = map.get(key);
                List listOfValues = new ArrayList<Object>();
                if (value instanceof List) {
                    listOfValues = (List<Object>) value;
                } else {
                    listOfValues.add(value);
                }
                listOfValues.add(toAdd);
                map.put(key, listOfValues);
            } else {
                map.put(key, toAdd);
            }
        }
    }
    return map;
}

From source file:org.fseek.simon.imageuploader.hoster.imgur.ImgurUploader.java

License:Open Source License

private void parseXML(Element n, ImgurImage img) throws Exception {
    addToEngine(n, img);/* w  ww  . java  2 s  .c  om*/
    for (int i = 0; i < n.nodeCount(); i++) {
        Node node = n.node(i);
        if (node instanceof Element) {
            parseXML((Element) node, img);
        }
    }
}

From source file:org.nuxeo.automation.scripting.blockly.converter.Chains2Blockly.java

License:Open Source License

protected List<Element> findPlaceHolders(Element root) {
    List<Element> result = new ArrayList<Element>();
    for (int i = 0, size = root.nodeCount(); i < size; i++) {
        Node node = root.node(i);
        if (node instanceof Element) {
            Element e = (Element) node;
            if (e.getName().equals("placeHolder")) {
                result.add(e);/*from   w  w  w  . j a va2s. com*/
            }
            result.addAll(findPlaceHolders(e));
        }
    }
    return result;
}

From source file:org.nuxeo.ecm.platform.webdav.helpers.DavRequestXMLHelper.java

License:Open Source License

@SuppressWarnings("unchecked")
public static DavLockInfo extractLockInfo(Element root) {

    DavLockInfo lockInfo = new DavLockInfo();

    if (root == null) {
        return lockInfo;
    }/*  w ww .j av a  2  s  . c  o  m*/

    Iterator<Element> eiter = root.elementIterator();

    while (eiter.hasNext()) {
        Element child = eiter.next();
        String tagName = child.getName();
        String uri = child.getNamespace().getURI();
        if (uri.equals(WebDavConst.DAV_XML_URI) && tagName.equals("lockinfo")) {
            Iterator<Element> citer = child.elementIterator();
            while (citer.hasNext()) {
                Element subChild = citer.next();
                if (uri.equals(WebDavConst.DAV_XML_URI) && tagName.equals("owner")) {
                    if (subChild.nodeCount() > 0) {
                        lockInfo.setOwner(subChild.getText());
                    } else {
                        lockInfo.setOwner(subChild.node(0).getStringValue());
                    }
                }
            }
            return lockInfo;
        }
    }

    return lockInfo;
}

From source file:org.openadaptor.auxil.connector.jdbc.writer.xml.AbstractXMLWriter.java

License:Open Source License

private void populateStatementFromElements(Element root) throws SQLException {
    for (int i = 0; i < root.nodeCount(); i++) {
        Node node = root.node(i);
        populateParameter(i + 1, node.getStringValue());
    }/*  w  w w .j av  a 2  s  . c om*/
}

From source file:org.openadaptor.auxil.convertor.xml.XmlToOrderedMapConvertor.java

License:Open Source License

/**
 * Convert an Element into an orderedMap. essentially loops through each child
 * node of the supplied element and add a corresponding attribute to the ordered
 * map.//w  w w .ja v a  2 s .co  m
 *
 * @param current the element to convert
 *
 * @return the equivalent IOrderedMap
 *
 * @throws RecordException if there was a problem decoding the value
 */
private IOrderedMap generateMapFromXml(Element current) throws RecordException {
    IOrderedMap map = new OrderedHashMap(); //ToDo: Decouple OHM Dependency - i.e. make this factory generated.

    //This is faster than iterator
    for (int i = 0, size = current.nodeCount(); i < size; i++) {
        Node node = current.node(i);

        //It will need to be added
        if (node instanceof Element) {
            Element element = (Element) node;
            String name = element.getName();
            log.debug("Mapping Element:" + name);

            insert(map, name, generateValue(element));
        }
    }

    return map;
}

From source file:org.orbeon.oxf.processor.sql.SQLProcessor.java

License:Open Source License

protected void execute(final PipelineContext context, XMLReceiver xmlReceiver) {
    try {//  w w  w  .j  a  v a  2 s.  c  o  m
        // Cache, read and interpret the config input
        Config config = readCacheInputAsObject(context, getInputByName(INPUT_CONFIG),
                new CacheableInputReader<Config>() {
                    public Config read(PipelineContext context, ProcessorInput input) {
                        // Read the config input document
                        Node config = readInputAsDOM4J(context, input);
                        Document configDocument = config.getDocument();

                        // Extract XPath expressions and also check whether any XPath expression is used at all
                        // NOTE: This could be done through streaming below as well
                        // NOTE: For now, just match <sql:param select="/*" type="xs:base64Binary"/>
                        List xpathExpressions = new ArrayList();
                        boolean useXPathExpressions = false;
                        for (Iterator i = XPathUtils.selectIterator(configDocument,
                                "//*[namespace-uri() = '" + SQL_NAMESPACE_URI + "' and @select]"); i
                                        .hasNext();) {
                            Element element = (Element) i.next();
                            useXPathExpressions = true;
                            String typeAttribute = element.attributeValue("type");
                            if ("xs:base64Binary".equals(typeAttribute)) {
                                String selectAttribute = element.attributeValue("select");
                                xpathExpressions.add(selectAttribute);
                            }
                        }

                        // Normalize spaces. What this does is to coalesce adjacent text nodes, and to remove
                        // resulting empty text, unless the text is contained within a sql:text element.
                        configDocument.accept(new VisitorSupport() {
                            private boolean endTextSequence(Element element, Text previousText) {
                                if (previousText != null) {
                                    String value = previousText.getText();
                                    if (value == null || value.trim().equals("")) {
                                        element.remove(previousText);
                                        return true;
                                    }
                                }
                                return false;
                            }

                            @Override
                            public void visit(Element element) {
                                // Don't touch text within sql:text elements
                                if (!SQL_NAMESPACE_URI.equals(element.getNamespaceURI())
                                        || !"text".equals(element.getName())) {
                                    Text previousText = null;
                                    for (int i = 0, size = element.nodeCount(); i < size;) {
                                        Node node = element.node(i);
                                        if (node instanceof Text) {
                                            Text text = (Text) node;
                                            if (previousText != null) {
                                                previousText.appendText(text.getText());
                                                element.remove(text);
                                            } else {
                                                String value = text.getText();
                                                // Remove empty text nodes
                                                if (value == null || value.length() < 1) {
                                                    element.remove(text);
                                                } else {
                                                    previousText = text;
                                                    i++;
                                                }
                                            }
                                        } else {
                                            if (!endTextSequence(element, previousText))
                                                i++;
                                            previousText = null;
                                        }
                                    }
                                    endTextSequence(element, previousText);
                                }
                            }
                        });
                        // Create SAXStore
                        try {
                            final SAXStore store = new SAXStore();
                            final LocationSAXWriter locationSAXWriter = new LocationSAXWriter();
                            locationSAXWriter.setContentHandler(store);
                            locationSAXWriter.write(configDocument);
                            // Return the normalized document
                            return new Config(store, useXPathExpressions, xpathExpressions);
                        } catch (SAXException e) {
                            throw new OXFException(e);
                        }
                    }
                });

        // Either read the whole input as a DOM, or try to serialize
        Node data = null;
        XPathXMLReceiver xpathReceiver = null;

        // Check if the data input is connected
        boolean hasDataInput = getConnectedInputs().get(INPUT_DATA) != null;
        if (!hasDataInput && config.useXPathExpressions)
            throw new OXFException(
                    "The data input must be connected when the configuration uses XPath expressions.");
        if (!hasDataInput || !config.useXPathExpressions) {
            // Just use an empty document
            data = Dom4jUtils.NULL_DOCUMENT;
        } else {
            // There is a data input connected and there are some XPath expressions operating on it
            boolean useXPathContentHandler = false;
            if (config.xpathExpressions.size() > 0) {
                // Create XPath content handler
                final XPathXMLReceiver _xpathReceiver = new XPathXMLReceiver();
                // Add expressions and check whether we can try to stream
                useXPathContentHandler = true;
                for (Iterator i = config.xpathExpressions.iterator(); i.hasNext();) {
                    String expression = (String) i.next();
                    boolean canStream = _xpathReceiver.addExpresssion(expression, false);// FIXME: boolean nodeSet
                    if (!canStream) {
                        useXPathContentHandler = false;
                        break;
                    }
                }
                // Finish setting up the XPathContentHandler
                if (useXPathContentHandler) {
                    _xpathReceiver.setReadInputCallback(new Runnable() {
                        public void run() {
                            readInputAsSAX(context, INPUT_DATA, _xpathReceiver);
                        }
                    });
                    xpathReceiver = _xpathReceiver;
                }
            }
            // If we can't stream, read everything in
            if (!useXPathContentHandler)
                data = readInputAsDOM4J(context, INPUT_DATA);
        }

        // Try to read datasource input if any
        Datasource datasource = null;
        {
            List datasourceInputs = (List) getConnectedInputs().get(INPUT_DATASOURCE);
            if (datasourceInputs != null) {
                if (datasourceInputs.size() > 1)
                    throw new OXFException("At most one one datasource input can be connected.");
                ProcessorInput datasourceInput = (ProcessorInput) datasourceInputs.get(0);
                datasource = Datasource.getDatasource(context, this, datasourceInput);
            }
        }

        // Replay the config SAX store through the interpreter
        config.configInput.replay(
                new RootInterpreter(context, getPropertySet(), data, datasource, xpathReceiver, xmlReceiver));
    } catch (OXFException e) {
        throw e;
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.xforms.xbl.XBLTransformer.java

License:Open Source License

/**
 * Apply an XBL transformation, i.e. apply xbl:content, xbl:attr, etc.
 *
 * NOTE: This mutates shadowTreeDocument.
 *//*from w w  w.  j  a  va 2s  .co m*/
public static Document transform(final Document shadowTreeDocument, final Element boundElement,
        final boolean excludeNestedHandlers, final boolean excludeNestedLHHA) {

    final DocumentWrapper documentWrapper = new DocumentWrapper(boundElement.getDocument(), null,
            XPathCache.getGlobalConfiguration());

    Dom4jUtils.visitSubtree(shadowTreeDocument.getRootElement(), new Dom4jUtils.VisitorListener() {

        boolean isNestedHandler(Element e) {
            return e.getParent() == boundElement && EventHandlerImpl.isEventHandler(e);
        }

        boolean isNestedLHHA(Element e) {
            return e.getParent() == boundElement && LHHA.isLHHA(e);
        }

        boolean mustFilterOut(Element e) {
            return excludeNestedHandlers && isNestedHandler(e) || excludeNestedLHHA && isNestedLHHA(e);
        }

        public void startElement(Element element) {

            // Handle xbl:content

            final boolean isXBLContent = element.getQName().equals(XBL_CONTENT_QNAME);
            final List<Node> resultingNodes;
            if (isXBLContent) {
                final String includesAttribute = element.attributeValue(XFormsConstants.INCLUDES_QNAME);
                final String scopeAttribute = element.attributeValue(XFormsConstants.XXBL_SCOPE_QNAME);
                final List<Node> contentToInsert;
                if (includesAttribute == null) {
                    // All bound node content must be copied over (except nested handlers if requested)
                    final List<Node> elementContent = Dom4jUtils.content(boundElement);
                    final List<Node> clonedContent = new ArrayList<Node>();
                    for (final Node node : elementContent) {
                        if (node instanceof Element) {
                            final Element currentElement = (Element) node;
                            if (!mustFilterOut(currentElement))
                                clonedContent.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement));
                        } else if (!(node instanceof Namespace)) {
                            clonedContent.add(Dom4jUtils.createCopy(node));
                        }
                    }

                    contentToInsert = clonedContent;
                } else {
                    // Apply CSS selector

                    // Convert CSS to XPath
                    final String xpathExpression = CSSParser.toXPath(includesAttribute);

                    final NodeInfo boundElementInfo = documentWrapper.wrap(boundElement);

                    // TODO: don't use getNamespaceContext() as this is already computed for the bound element
                    final List<Object> elements = XPathCache.evaluate(boundElementInfo, xpathExpression,
                            new NamespaceMapping(Dom4jUtils.getNamespaceContext(element)), null, null, null,
                            null, null, null);// TODO: locationData

                    if (elements.size() > 0) {
                        // Clone all the resulting elements
                        contentToInsert = new ArrayList<Node>(elements.size());
                        for (Object o : elements) {
                            final NodeInfo currentNodeInfo = (NodeInfo) o;
                            final Element currentElement = (Element) ((VirtualNode) currentNodeInfo)
                                    .getUnderlyingNode();

                            if (!mustFilterOut(currentElement))
                                contentToInsert.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement));
                        }
                    } else {
                        // Clone all the element's children if any
                        // See: http://www.w3.org/TR/xbl/#the-content
                        contentToInsert = new ArrayList<Node>(element.nodeCount());
                        for (Object o : element.elements()) {
                            final Element currentElement = (Element) o;
                            if (!mustFilterOut(currentElement))
                                contentToInsert.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement));
                        }
                    }
                }

                // Insert content if any
                if (contentToInsert != null && contentToInsert.size() > 0) {
                    final List<Node> parentContent = Dom4jUtils.content(element.getParent());
                    final int elementIndex = parentContent.indexOf(element);
                    parentContent.addAll(elementIndex, contentToInsert);
                }

                // Remove <xbl:content> from shadow tree
                element.detach();

                resultingNodes = contentToInsert;

                if (!StringUtils.isBlank(scopeAttribute)) {
                    // If author specified scope attribute, use it
                    setAttribute(resultingNodes, XFormsConstants.XXBL_SCOPE_QNAME, scopeAttribute, null);
                } else {
                    // By default, set xxbl:scope="outer" on resulting elements
                    setAttribute(resultingNodes, XFormsConstants.XXBL_SCOPE_QNAME, "outer", null);
                }
            } else {
                // Element is simply kept
                resultingNodes = Collections.singletonList((Node) element);
            }

            // Handle attribute forwarding
            final Attribute xblAttr = element.attribute(XBL_ATTR_QNAME); // standard xbl:attr (custom syntax)
            final Attribute xxblAttr = element.attribute(XXBL_ATTR_QNAME); // extension xxbl:attr (XPath expression)
            if (xblAttr != null) {
                // Detach attribute (not strictly necessary?)
                xblAttr.detach();
                // Get attribute value
                final String xblAttrString = xblAttr.getValue();
                final StringTokenizer st = new StringTokenizer(xblAttrString);
                while (st.hasMoreTokens()) {
                    final String currentValue = st.nextToken();

                    final int equalIndex = currentValue.indexOf('=');
                    if (equalIndex == -1) {
                        // No a=b pair, just a single QName
                        final QName valueQName = Dom4jUtils.extractTextValueQName(element, currentValue, true);
                        if (!valueQName.getNamespaceURI().equals(XFormsConstants.XBL_NAMESPACE_URI)) {
                            // This is not xbl:text, copy the attribute
                            setAttribute(resultingNodes, valueQName, boundElement.attributeValue(valueQName),
                                    boundElement);
                        } else {
                            // This is xbl:text
                            // "The xbl:text value cannot occur by itself in the list"
                        }

                    } else {
                        // a=b pair
                        final QName leftSideQName;
                        {
                            final String leftSide = currentValue.substring(0, equalIndex);
                            leftSideQName = Dom4jUtils.extractTextValueQName(element, leftSide, true);
                        }
                        final QName rightSideQName;
                        {
                            final String rightSide = currentValue.substring(equalIndex + 1);
                            rightSideQName = Dom4jUtils.extractTextValueQName(element, rightSide, true);
                        }

                        final boolean isLeftSideXBLText = leftSideQName.getNamespaceURI()
                                .equals(XFormsConstants.XBL_NAMESPACE_URI);
                        final boolean isRightSideXBLText = rightSideQName.getNamespaceURI()
                                .equals(XFormsConstants.XBL_NAMESPACE_URI);

                        final String rightSideValue;
                        final Element namespaceElement;
                        if (!isRightSideXBLText) {
                            // Get attribute value
                            rightSideValue = boundElement.attributeValue(rightSideQName);
                            namespaceElement = boundElement;
                        } else {
                            // Get text value

                            // "any text nodes (including CDATA nodes and whitespace text nodes) that are
                            // explicit children of the bound element must have their data concatenated"
                            rightSideValue = boundElement.getText();// must use getText() and not stringValue()
                            namespaceElement = null;
                        }

                        if (rightSideValue != null) {
                            // NOTE: XBL doesn't seem to says what should happen if the source attribute is not
                            // found! We assume the rule is ignored in this case.
                            if (!isLeftSideXBLText) {
                                // Set attribute value
                                setAttribute(resultingNodes, leftSideQName, rightSideValue, namespaceElement);
                            } else {
                                // Set text value

                                // "value of the attribute on the right-hand side are to be represented as text
                                // nodes underneath the shadow element"

                                // TODO: "If the element has any child nodes in the DOM (any nodes, including
                                // comment nodes, whitespace text nodes, or even empty CDATA nodes) then the pair
                                // is in error and UAs must ignore it, meaning the attribute value is not forwarded"

                                setText(resultingNodes, rightSideValue);
                            }
                        }
                    }
                    // TODO: handle xbl:lang?
                    // TODO: handle type specifiers?
                }
            } else if (xxblAttr != null) {
                // Detach attribute (not strictly necessary?)
                xxblAttr.detach();
                // Get attribute value
                final String xxblAttrString = xxblAttr.getValue();

                final NodeInfo boundElementInfo = documentWrapper.wrap(boundElement);

                // TODO: don't use getNamespaceContext() as this is already computed for the bound element
                final List<Object> nodeInfos = XPathCache.evaluate(boundElementInfo, xxblAttrString,
                        new NamespaceMapping(Dom4jUtils.getNamespaceContext(element)), null, null, null, null,
                        null, null);// TODO: locationData

                if (nodeInfos.size() > 0) {
                    for (Object nodeInfo : nodeInfos) {
                        final NodeInfo currentNodeInfo = (NodeInfo) nodeInfo;
                        if (currentNodeInfo.getNodeKind() == org.w3c.dom.Node.ATTRIBUTE_NODE) {
                            // This is an attribute
                            final Attribute currentAttribute = (Attribute) ((VirtualNode) currentNodeInfo)
                                    .getUnderlyingNode();
                            setAttribute(resultingNodes, currentAttribute.getQName(),
                                    currentAttribute.getValue(), currentAttribute.getParent());
                        }
                    }
                }
            }

            // Prefix resulting xhtml:*/(@id |@for)

            // NOTE: We could also do the prefixing in the handlers, when the page is output.
            //
            // * Benefit of prefixing here: done statically
            // * Drawback of prefixing here: in the future if we try to reuse simple shadow trees this won't work

            //                    {
            //                        if (resultingNodes != null && resultingNodes.size() > 0) {
            //                            for (Iterator i = resultingNodes.iterator(); i.hasNext();) {
            //                                final Node node = (Node) i.next();
            //                                if (node instanceof Element) {
            //                                    Dom4jUtils.visitSubtree((Element) node, new Dom4jUtils.VisitorListener() {
            //                                        public void startElement(Element element) {
            //                                            if (XMLConstants.XHTML_NAMESPACE_URI.equals(element.getNamespaceURI())) {
            //                                                // Found XHTML element
            //
            //                                                // Update @id and @for if any
            //                                                final Attribute idAttribute = element.attribute("id");
            //                                                if (idAttribute != null) {
            //                                                    idAttribute.setValue(prefix + idAttribute.getValue());
            //                                                }
            //                                                final Attribute forAttribute = element.attribute("for");
            //                                                if (forAttribute != null) {
            //                                                    forAttribute.setValue(prefix + forAttribute.getValue());
            //                                                }
            //                                            }
            //                                        }
            //
            //                                        public void endElement(Element element) {
            //                                        }
            //
            //                                        public void text(Text text) {
            //                                        }
            //                                    });
            //                                }
            //                            }
            //                        }
            //                    }
        }

        private void setAttribute(List<Node> nodes, QName attributeQName, String attributeValue,
                Element namespaceElement) {
            if (nodes != null && nodes.size() > 0) {
                for (final Node node : nodes) {
                    if (node instanceof Element) {
                        final Element element = ((Element) node);
                        // Copy missing namespaces, so that copying things like ref="foo:bar" work as expected
                        Dom4jUtils.copyMissingNamespaces(namespaceElement, element);
                        element.addAttribute(attributeQName, attributeValue);
                    }
                }
            }
        }

        private void setText(List<Node> nodes, String value) {
            if (nodes != null && nodes.size() > 0) {
                for (final Node node : nodes) {
                    if (node instanceof Element) {
                        node.setText(value);
                    }
                }
            }
        }

        public void endElement(Element element) {
        }

        public void text(Text text) {
        }
    }, true);

    return shadowTreeDocument;
}

From source file:org.pentaho.di.ui.trans.steps.getxmldata.GetXMLDataDialog.java

License:Open Source License

private void ChildNode(Node node, String realXPath, String realXPathCleaned) {
    Element ce = (Element) node;
    // List child 
    for (int j = 0; j < ce.nodeCount(); j++) {
        Node cnode = ce.node(j);/*from  w  ww  .  ja  va 2  s .  c  o  m*/
        if (!Const.isEmpty(cnode.getName())) {
            Element cce = (Element) cnode;
            if (cce.nodeCount() > 1) {
                if (Const.getOccurenceString(cnode.asXML(), "/>") <= 1) {
                    // We do not have child nodes ...
                    setNodeField(cnode, realXPathCleaned);
                } else {
                    // let's get child nodes
                    ChildNode(cnode, realXPath, realXPathCleaned);
                }
            } else {
                setNodeField(cnode, realXPathCleaned);
            }
        }
    }
}