Example usage for org.w3c.dom Node TEXT_NODE

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

Introduction

In this page you can find the example usage for org.w3c.dom Node TEXT_NODE.

Prototype

short TEXT_NODE

To view the source code for org.w3c.dom Node TEXT_NODE.

Click Source Link

Document

The node is a Text node.

Usage

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void insertBefore(NodeList nodes, Node newNode, short newNodeType) {
    Node currentNode = nodes.item(0);
    switch (newNodeType) {
    case Node.ATTRIBUTE_NODE:
        Element parent = ((Attr) currentNode).getOwnerElement();
        parent.setAttributeNode((Attr) newNode);
        break;/*from   w ww.j  a  v a  2 s.  co  m*/
    case Node.ELEMENT_NODE:
        currentNode.getParentNode().insertBefore(newNode, currentNode);
        break;
    case Node.TEXT_NODE:
        String v = currentNode.getNodeValue();
        currentNode.setNodeValue(newNode.getNodeValue() + v);
        break;
    }
}

From source file:architecture.ee.jdbc.sqlquery.builder.xml.XmlStatementBuilder.java

private List<SqlNode> parseDynamicTags(XNode node) {
    List<SqlNode> contents = new ArrayList<SqlNode>();
    NodeList children = node.getNode().getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        XNode child = node.newXNode(children.item(i));
        String nodeName = child.getNode().getNodeName();
        if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE
                || child.getNode().getNodeType() == Node.TEXT_NODE) {
            String data = child.getStringBody("");
            contents.add(new TextSqlNode(data));
        } else {//from  www .  j  av  a  2 s.  c o m
            if ("dynamic".equals(nodeName)) {
                String data = child.getStringBody("");
                contents.add(new DynamicSqlNode(data));
            }
        }
    }
    return contents;
}

From source file:de.fau.cs.osr.hddiff.perfsuite.RunFcDiff.java

private void processTextNodeContent(DiffNode parentA, DiffNode refWomA, DiffNode womB, NodeList diffChildren) {
    @SuppressWarnings("unused")
    String diffText;/*from  w  w  w. j av  a  2s. c  o m*/

    Node text = diffChildren.item(0);
    if (text.getNodeType() != Node.TEXT_NODE) {
        if (!cmpTag(text, NS_DIFF, "copy"))
            fcDiffConfusesMe();

        DiffNode[] run = getWomRun(parentA, (Element) text);
        if ((run.length != 1) || (run[0].getClass() != refWomA.getClass()))
            fcDiffConfusesMe();

        diffText = run[0].getTextContent();
    } else {
        diffText = text.getTextContent();
    }

    // no use, fcdiff messes with spaces :(
    /*
    diffText = StringEscapeUtils.unescapeXml(diffText);
    diffText = diffText.replaceAll("\\s+", "");
    String newText = womB.getTextContent();
    newText = newText.replaceAll("\\s+", "");
            
    if (!cmpStr(diffText, newText))
       fcDiffConfusesMe();
    */
}

From source file:importer.handler.post.stages.Discriminator.java

/**
 * Are two elements next to each other?/*from   w ww.ja  v a  2s  .  c  om*/
 * @param s1 the LHS element
 * @param s2 the RHS element
 * @return true if s1 is just before s2
 */
boolean areAdjacent(Element s1, Element s2) {
    Node n = s1;
    while (n != null) {
        n = n.getNextSibling();
        if (n != null) {
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n == s2)
                    return true;
            } else if (n.getNodeType() == Node.TEXT_NODE) {
                if (!isWhitespace(n.getTextContent()))
                    break;
            }
        }
    }
    return false;
}

From source file:com.sun.faces.config.rules.DescriptionTextRule.java

/**
 * <p>Append the serialized version of the specified node to the
 * string buffer being accumulated.</p>
 *
 * @param sb StringBuffer to which serialized text is appended
 * @param node Node to be serialized//  w  w  w.  j a v  a  2s . c o m
 *
 * @exception Exception if any processing exception occurs
 */
private void serialize(StringBuffer sb, Node node) throws Exception {

    // Processing depends on the node type
    switch (node.getNodeType()) {

    case Node.ELEMENT_NODE:

        if (digester.getLogger().isDebugEnabled()) {
            digester.getLogger().debug("  Processing element node '" + node.getNodeName() + "'");
        }

        // Open the element and echo the attributes
        sb.append("<");
        sb.append(node.getNodeName());
        NamedNodeMap attrs = node.getAttributes();
        int n = attrs.getLength();
        for (int i = 0; i < n; i++) {
            Node attr = attrs.item(i);
            sb.append(" ");
            sb.append(attr.getNodeName());
            sb.append("=\"");
            sb.append(attr.getNodeValue());
            sb.append("\"");
        }

        // Does this element have any children?
        NodeList kids = node.getChildNodes();
        int m = kids.getLength();
        if (m > 0) {

            // Yes -- serialize child elements and close parent element
            sb.append(">");
            for (int j = 0; j < m; j++) {
                serialize(sb, kids.item(j));
            }
            sb.append("</");
            sb.append(node.getNodeName());
            sb.append(">");

        } else {

            // No -- shorthand close of the parent element
            sb.append(" />");

        }
        break;

    case Node.TEXT_NODE:

        if (digester.getLogger().isDebugEnabled()) {
            digester.getLogger().debug("  Processing text node '" + node.getNodeValue() + "'");
        }

        // Append the text to our accumulating buffer
        sb.append(node.getNodeValue());
        break;

    default:
        throw new IllegalArgumentException(
                "Cannot process node '" + node.getNodeName() + "' of type '" + node.getNodeType());

    }

}

From source file:edu.indiana.lib.twinpeaks.util.DomUtils.java

/**
 * Get any text associated with this element and it's children.  Null if none.
 * @param parent the node containing text
 * @return Text/*w  w w  .  ja va 2s.  com*/
 */
public static String getAllText(Node parent) {
    String text = null;

    if (parent != null) {

        for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {

            if (child.getNodeType() == Node.TEXT_NODE) {
                text = normalizeText(text, child.getNodeValue());
                continue;
            }

            if (child.getNodeType() == Node.ELEMENT_NODE) {
                String childText = getText(child);

                if (childText != null) {
                    text = normalizeText(text, childText);
                }
            }
        }
    }
    return text;
}

From source file:com.streamsets.pipeline.stage.processor.xmlflattener.XMLFlatteningProcessor.java

private void processXML(Record record, boolean currentlyInRecord, XMLNode current, List<Record> recordList,
        Record originalRecord) throws DOMException {
    NodeList nodeList = current.element.getChildNodes();
    // Preprocess the child Nodes to avoid having to do it each time we hit a new element.
    if (currentlyInRecord) {
        Set<String> nodes = new HashSet<>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node next = nodeList.item(i);
            if (next.getNodeType() == Node.ELEMENT_NODE) {
                Element e = (Element) next;
                // We already saw the same name once before. Add it to the current element's map.
                if (nodes.contains(e.getTagName()) && !current.nodeCounters.containsKey(e.getTagName())) {
                    current.nodeCounters.put(e.getTagName(), 0);
                } else {
                    nodes.add(e.getTagName());
                }//ww w .j  a  v  a2  s. c om
            }
        }
    }
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node next = nodeList.item(i);
        // Text node - add it as a field, if we are currently in a record
        if (currentlyInRecord && next.getNodeType() == Node.TEXT_NODE) {
            String text = ((Text) next).getWholeText();
            if (text.trim().isEmpty()) {
                continue;
            }
            // If we don't need to keep existing fields, just write
            // If we need to keep existing fields, overwrite only if the original field does not exist
            // If we need to keep existing fields, and the current record has the path, overwrite only if newFieldsOverwrite
            if (!keepExistingFields || !record.has(getPathPrefix() + current.prefix) || newFieldsOverwrite) {
                ensureOutputFieldExists(record);
                record.set(getPathPrefix() + current.prefix, Field.create(text));
            }
        } else if (next.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) next;
            String tagName = element.getTagName();
            String elementPrefix;

            // If we are not in a record and this is the delimiter, then create a new record to fill in.
            if (!currentlyInRecord && element.getNodeName().equals(recordDelimiter)) {
                // Create a new record
                elementPrefix = tagName;

                //Increment record count
                flattenerPerRecordCount++;

                Record newR;
                //Add the node index as sourceRecordIdPostFix for newly created/cloned record.
                if (keepExistingFields) {
                    newR = getContext().cloneRecord(originalRecord, String.valueOf(flattenerPerRecordCount));
                } else {
                    newR = getContext().createRecord(originalRecord, String.valueOf(flattenerPerRecordCount));
                    newR.set(Field.create(new HashMap<String, Field>()));
                }
                ensureOutputFieldExists(newR);
                recordList.add(newR);
                addAttrs(newR, element, elementPrefix);
                processXML(newR, true, new XMLNode(element, tagName), recordList, record);
            } else { // This is not a record delimiter, or we are currently already in a record
                // Check if this is the first time we are seeing this prefix?
                // The map tracks the next index to append. If the map does not have the key, don't add an index.
                elementPrefix = current.prefix + fieldDelimiter + tagName;
                if (current.nodeCounters.containsKey(tagName)) {
                    Integer nextCount = current.nodeCounters.get(tagName);
                    elementPrefix = elementPrefix + "(" + nextCount.toString() + ")";
                    current.nodeCounters.put(tagName, nextCount + 1);
                }
                if (currentlyInRecord) {
                    addAttrs(record, element, elementPrefix);
                }
                XMLNode nextNode = new XMLNode(element, elementPrefix);
                processXML(record, currentlyInRecord, nextNode, recordList, record);
            }
        }
    }
}

From source file:it.delli.mwebc.servlet.MWebCRenderer.java

public static void buildLayout(Element elem, Widget parent, Page page) throws Exception {
    Widget widget = null;//from www  .  j a  v a 2  s. c  o m
    if (elem.getNodeType() == Node.ELEMENT_NODE && elem.getNodeName().equals("Page")) {
        for (int j = 0; j < elem.getAttributes().getLength(); j++) {
            Node attribute = elem.getAttributes().item(j);
            if (!attribute.getNodeName().equals("id")) {
                if (attribute.getNodeName().equals("eventListener")) {
                    log.debug("Setting PageEventListener");
                    try {
                        page.setEventListener(
                                (PageEventListener) Class.forName(attribute.getNodeValue()).newInstance());
                    } catch (Exception e) {
                        log.error("Exception in setting PageEventListener");
                    }
                }
            }
        }
        if (page.getEventListener() == null) {
            log.debug("Setting default PageEventListener");
            page.setEventListener(new PageEventListener() {

                @Override
                public void onLoad(Event event) {
                }

                @Override
                public void onInit(Event event) {
                }

            });
        }
        for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
            Node node = elem.getChildNodes().item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                buildLayout((Element) node, widget, page);
            }
        }
    } else if (elem.getNodeType() == Node.ELEMENT_NODE && elem.getNodeName().equals("PageFragment")) {
        for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
            Node node = elem.getChildNodes().item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                buildLayout((Element) node, parent, page);
            }
        }
    } else {
        Class<?> widgetClass = page.getApplication().getWidgetClass(elem.getNodeName());
        if (widgetClass == null) {
            log.fatal("Exception in getting widget class for widget " + elem.getNodeName());
            throw new Exception();
        } else if (widgetClass.getName().equals("com.dodifferent.applications.commander.widget.DataListItem")) {
            System.out.println();
        }
        CastHelper castHelper = page.getApplication().getCastHelper(widgetClass);

        String id = null;
        for (int j = 0; j < elem.getAttributes().getLength(); j++) {
            Node attribute = elem.getAttributes().item(j);
            if (attribute.getNodeName().equals("id")) {
                id = attribute.getNodeValue();
                break;
            }
        }

        HashMap<String, Object> initParams = new HashMap<String, Object>();
        for (int j = 0; j < elem.getAttributes().getLength(); j++) {
            Node attributeNode = elem.getAttributes().item(j);
            if (!attributeNode.getNodeName().equals("id") && !attributeNode.getNodeName().startsWith("on")) {
                Field fieldAttribute = ReflectionUtils.getAnnotatedField(widgetClass,
                        attributeNode.getNodeName(), WidgetAttribute.class);
                if (fieldAttribute != null) {
                    fieldAttribute.setAccessible(true);
                    Class<?> propertyType = fieldAttribute.getType();
                    //                  Type[] genericTypes = ((ParameterizedType)fieldAttribute.getGenericType()).getActualTypeArguments();
                    initParams.put(attributeNode.getNodeName(),
                            castHelper.toType(attributeNode.getNodeValue(), propertyType));
                } else {
                    log.warn("Warning in updating server widgets attribute. The attribute '"
                            + attributeNode.getNodeName() + "' doesn't exist for widget "
                            + widgetClass.getName());
                }
            }
        }

        try {
            if (id != null && initParams.keySet().size() == 0) {
                Class[] constructorParams = { Page.class, String.class };
                Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                        .getConstructor(constructorParams);
                widget = (Widget) widgetConstructor.newInstance(page, id);
            } else if (id != null && initParams.keySet().size() > 0) {
                Class[] constructorParams = { Page.class, String.class, Map.class };
                Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                        .getConstructor(constructorParams);
                widget = (Widget) widgetConstructor.newInstance(page, id, initParams);
            } else if (id == null && initParams.keySet().size() == 0) {
                Class[] constructorParams = { Page.class };
                Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                        .getConstructor(constructorParams);
                widget = (Widget) widgetConstructor.newInstance(page);
            } else if (id == null && initParams.keySet().size() > 0) {
                Class[] constructorParams = { Page.class, Map.class };
                Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                        .getConstructor(constructorParams);
                widget = (Widget) widgetConstructor.newInstance(page, initParams);
            }
        } catch (Exception e) {
            log.error("Exception in constructing widget " + widget.getClass().getName() + " (" + widget.getId()
                    + ")", e);
        }

        if (widget != null) {
            for (int j = 0; j < elem.getAttributes().getLength(); j++) {
                Node attributeNode = elem.getAttributes().item(j);
                if (!attributeNode.getNodeName().equals("id") && attributeNode.getNodeName().startsWith("on")) {
                    String event = attributeNode.getNodeName();
                    try {
                        widget.addEventListener(event, page.getEventListener(), attributeNode.getNodeValue());
                        //                     Method eventMethod = widget.getClass().getMethod("addEventListener", String.class, EventListener.class, String.class);
                        //                     eventMethod.invoke(widget, event, page.getEventListener(), attributeNode.getNodeValue());
                    } catch (Exception e) {
                        log.warn("Warning in registering EventListener for widget "
                                + widget.getClass().getName() + " (" + widget.getId() + ")", e);
                    }
                }
            }
            for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
                Node node = elem.getChildNodes().item(i);
                if (node.getNodeType() == Node.CDATA_SECTION_NODE || node.getNodeType() == Node.TEXT_NODE) {
                    try {
                        String content = node.getNodeValue().replace("\t", "").replace("\n", "").replace("\"",
                                "\\\"");
                        if (!content.equals("")) {
                            //                        Method attributeMethod = widget.getClass().getMethod("addTextContent", String.class);
                            //                        attributeMethod.invoke(widget, content);
                            widget.addTextContent(content);
                        }
                    } catch (Exception e) {
                        log.warn("Warning in setting content for widget " + widget.getClass().getName() + " ("
                                + widget.getId() + ")", e);
                    }
                } else if (node.getNodeType() == Node.ELEMENT_NODE) {
                    buildLayout((Element) node, widget, page);
                }
            }
            widget.setParent(parent);
        }
    }
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void append(NodeList nodes, Node newNode, short newNodeType) {
    Node currentNode = nodes.item(0);
    switch (newNodeType) {
    case Node.ATTRIBUTE_NODE:
        Element parent = ((Attr) currentNode).getOwnerElement();
        parent.setAttributeNode((Attr) newNode);
        break;//from   w w  w  . jav a 2s  .  c o m
    case Node.ELEMENT_NODE:
        currentNode.appendChild(newNode);
        break;
    case Node.TEXT_NODE:
        if (currentNode.getNodeType() != Node.TEXT_NODE) {
            throw new IllegalStateException("wrong source node type.");
        }
        String v = currentNode.getNodeValue();
        currentNode.setNodeValue(v + newNode.getNodeValue());
        break;
    }
}

From source file:ValidateLicenseHeaders.java

/**
 * Get all non-comment content from the element.
 * //  w  w w.j ava 2  s .  c  o  m
 * @param element
 * @return the concatenated text/cdata content
 */
public static String getElementContent(Element element) {
    if (element == null)
        return null;

    NodeList children = element.getChildNodes();
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
            result.append(child.getNodeValue());
        } else if (child.getNodeType() == Node.COMMENT_NODE) {
            // Ignore comment nodes
        } else {
            result.append(child.getFirstChild());
        }
    }
    return result.toString().trim();
}