Example usage for org.w3c.dom Node COMMENT_NODE

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

Introduction

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

Prototype

short COMMENT_NODE

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

Click Source Link

Document

The node is a Comment.

Usage

From source file:Main.java

/**
 * Generates XPath expression with the option of the Node values appended
 *
 * @param node             the Node whose XPath is to be found
 * @param ignoreWhitespace the flag to indicate if Whitespace will be ignored
 * @param includeValues    the flag to indicate if Node values will be included
 * @param noIndex          the flag to indicate if Node indexes are included
 * @return the XPath string representation of the Node
 *//* w w  w.  j a v a  2 s.c  om*/

public static String generateXPath(Node node, boolean ignoreWhitespace, boolean includeValues, boolean noIndex)

{

    boolean noValues = !includeValues;

    if (node == null)

        return "";

    Node parent = node.getParentNode();

    int index = noIndex ? 0 : getXPathNodeIndex(node, ignoreWhitespace);

    String indexStr = "";

    if (index > 0)

        indexStr = "[" + Integer.toString(index) + "]";

    //printNode(node);

    //printNode(parent);

    if (node.getNodeType() == Node.DOCUMENT_NODE)

    {

        // return only the blank String, since all the other types are preceded with /

        return "";

    } else if (node.getNodeType() == Node.TEXT_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() + indexStr : "/TEXT(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ELEMENT_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                "/" + node.getNodeName() + indexStr;

    } else if (node.getNodeType() == Node.COMMENT_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() + indexStr
                        : "/COMMENT(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ENTITY_REFERENCE_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() + indexStr
                        : "/EntityReference(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() + indexStr : "/PI(" + node.getNodeValue() + ")" + indexStr);

    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE)

    {

        return generateXPath(((Attr) node).getOwnerElement(), ignoreWhitespace, noValues, noIndex) +

                "/'@" + node.getNodeName() +

                (noValues ? "" : "=" + node.getNodeValue()) + "]";

    } else if (node.getNodeType() == Node.DOCUMENT_TYPE_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() : "/DOCTYPE(" + node.getNodeName() + ")");

    } else if (node.getNodeType() == Node.CDATA_SECTION_NODE)

    {

        return generateXPath(parent, ignoreWhitespace, noValues, noIndex) +

                (noValues ? node.getNodeValue() : "/CDATA(" + node.getNodeName() + ")");

    }

    // Wont reach this far but just in case

    return "";

}

From source file:DOMCopy.java

private static void outputloop(Node node, String indent) {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            outputElement((Element) node, indent);
            break;
        case Node.TEXT_NODE:
            outputText((Text) node, indent);
            break;
        case Node.CDATA_SECTION_NODE:
            outputCDATASection((CDATASection) node, indent);
            break;
        case Node.COMMENT_NODE:
            outputComment((Comment) node, indent);
            break;
        case Node.PROCESSING_INSTRUCTION_NODE:
            outputProcessingInstructionNode((ProcessingInstruction) node, indent);
            break;
        default:/*from w w w .ja v a  2  s .c o m*/
            System.out.println("Unknown node type: " + node.getNodeType());
            break;
        }
    }

From source file:Main.java

protected static void print(PrintStream out, Node node) {
    if (node == null)
        return;//from ww  w .  j a va 2 s. c om
    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        // out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
        NodeList nodelist = node.getChildNodes();
        int size = nodelist.getLength();
        for (int i = 0; i < size; i++)
            print(out, nodelist.item(i));
        break;
    }

    case Node.DOCUMENT_TYPE_NODE: {
        DocumentType docType = (DocumentType) node;
        out.print("<!DOCTYPE " + getDocumentTypeData(docType) + ">\n");
        break;
    }

    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) {
            int size = map.getLength();
            for (int i = 0; i < size; i++) {
                Attr attr = (Attr) map.item(i);
                out.print(' ');
                out.print(attr.getNodeName());
                out.print("=\"");
                out.print(normalize(attr.getNodeValue()));
                out.print('"');
            }
        }

        if (!node.hasChildNodes())
            out.print("/>");
        else {
            out.print('>');
            NodeList nodelist = node.getChildNodes();
            int numChildren = nodelist.getLength();
            for (int i = 0; i < numChildren; i++)
                print(out, nodelist.item(i));

            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
        }
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: {
        NodeList nodelist = node.getChildNodes();
        if (nodelist != null) {
            int size = nodelist.getLength();
            for (int i = 0; i < size; i++)
                print(out, nodelist.item(i));

        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(node.getNodeName());
        String s = node.getNodeValue();
        if (s != null && s.length() > 0) {
            out.print(' ');
            out.print(s);
        }
        out.print("?>");
        break;
    }

    case Node.COMMENT_NODE: {
        out.print("<!--");
        out.print(node.getNodeValue());
        out.print("-->");
        break;
    }

    default: {
        out.print(normalize(node.getNodeValue()));
        break;
    }
    }
    out.flush();
}

From source file:ca.mcgill.music.ddmal.mei.MeiXmlReader.java

private MeiElement makeMeiElement(Node element) {
    // TODO: CDATA
    // Comments get a name #comment
    String nshref = element.getNamespaceURI();
    String nsprefix = element.getPrefix();
    MeiNamespace elns = new MeiNamespace(nshref, nsprefix);
    MeiElement e = new MeiElement(elns, element.getNodeName());
    if (element.getNodeType() == Node.COMMENT_NODE) {
        e.setValue(element.getNodeValue());
    }/*w ww.j  av  a  2s.  co m*/

    NamedNodeMap attributes = element.getAttributes();
    if (attributes != null) {
        for (int i = 0; i < attributes.getLength(); i++) {
            Node item = attributes.item(i);
            if (XML_ID_ATTRIBUTE.equals(item.getNodeName())) {
                e.setId(item.getNodeValue());
            } else {
                String attrns = item.getNamespaceURI();
                String attrpre = item.getPrefix();
                MeiNamespace atns = new MeiNamespace(attrns, attrpre);
                MeiAttribute a = new MeiAttribute(atns, item.getNodeName(), item.getNodeValue());
                e.addAttribute(a);
            }
        }
    }

    NodeList childNodes = element.getChildNodes();
    MeiElement lastElement = null;
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node item = childNodes.item(i);
        if (item.getNodeType() == Node.TEXT_NODE) {
            if (lastElement == null) {
                e.setValue(item.getNodeValue());
            } else {
                lastElement.setTail(item.getNodeValue());
            }
        } else {
            MeiElement child = makeMeiElement(item);
            e.addChild(child);
            lastElement = child;
        }
    }
    return e;
}

From source file:Main.java

/**
 * Performs the actual recursive dumping of a DOM tree to a given
 * <CODE>PrintStream</CODE>. Note that dump is intended to be a detailed
 * debugging aid rather than pretty to look at. 
 * //from  w  ww . j  a v a2  s. c om
 * @param    out            The <CODE>PrintStream</CODE> to write to.
 * @param    node         The <CODE>Node</CODE> under consideration.
 * @param    indent         The level of indentation.
 * @see      #dump(Node)
 * @see      #dump(PrintStream, Node)
 * @since   TFP 1.0
 */
private static void doDump(PrintStream out, final Node node, int indent) {
    if (node != null) {
        for (int index = 0; index < indent; ++index)
            out.write(' ');

        switch (node.getNodeType()) {
        case Node.DOCUMENT_NODE: {
            Document document = (Document) node;

            out.println("DOCUMENT:");

            doDump(out, document.getDoctype(), indent + 1);
            doDump(out, document.getDocumentElement(), indent + 1);
            break;
        }

        case Node.DOCUMENT_TYPE_NODE: {
            DocumentType type = (DocumentType) node;

            out.println("DOCTYPE: [" + "name=" + format(type.getName()) + "," + "publicId="
                    + format(type.getPublicId()) + "," + "systemId=" + format(type.getSystemId()) + "]");
            break;
        }

        case Node.ELEMENT_NODE: {
            Element element = (Element) node;

            out.println("ELEMENT: [" + "ns=" + format(element.getNamespaceURI()) + "," + "name="
                    + format(element.getLocalName()) + "]");

            NamedNodeMap attrs = element.getAttributes();

            for (int index = 0; index < attrs.getLength(); ++index)
                doDump(out, attrs.item(index), indent + 1);

            for (Node child = element.getFirstChild(); child != null;) {
                doDump(out, child, indent + 1);
                child = child.getNextSibling();
            }
            break;
        }
        case Node.ATTRIBUTE_NODE: {
            Attr attr = (Attr) node;

            out.println("ATTRIBUTE: [" + "ns=" + format(attr.getNamespaceURI()) + "," + "prefix="
                    + format(attr.getPrefix()) + "," + "name=" + format(attr.getLocalName()) + "," + "value="
                    + format(attr.getNodeValue()) + "]");
            break;
        }

        case Node.TEXT_NODE: {
            Text text = (Text) node;

            out.println("TEXT: [" + format(text.getNodeValue()) + "]");

            for (Node child = text.getFirstChild(); child != null;) {
                doDump(out, child, indent + 1);
                child = child.getNextSibling();
            }
            break;
        }

        case Node.CDATA_SECTION_NODE: {
            CDATASection data = (CDATASection) node;

            out.println("CDATA: [" + format(data.getNodeValue()) + "]");
            break;
        }

        case Node.COMMENT_NODE: {
            Comment comm = (Comment) node;

            out.println("COMMENT: [" + format(comm.getNodeValue()) + "]");
            break;
        }

        default:
            out.println("UNKNOWN: [type=" + node.getNodeType() + "]");
            break;
        }
    }
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

/**
 * Saves the configuration./*from w  w  w .j  av a 2s .  co m*/
 * @see IConfigurationManager#saveConfiguration()
 */
public synchronized void saveConfiguration() throws ConfigurationException {
    boolean bFound = false;
    Date dNow = null;
    StringBuffer sbComment = null;
    Element elRoot = null;
    Node nCurrent = null;
    Node nComment = null;
    String sValue = null;
    try {
        // add date to configuration
        dNow = new Date(System.currentTimeMillis());

        sbComment = new StringBuffer(" Configuration changes saved on ");
        sbComment.append(DateFormat.getDateInstance().format(dNow));
        sbComment.append(". ");

        elRoot = _oDomDocument.getDocumentElement();
        nCurrent = elRoot.getFirstChild();
        while (!bFound && nCurrent != null) // all elements
        {
            if (nCurrent.getNodeType() == Node.COMMENT_NODE) {
                // check if it's a "save changes" comment
                sValue = nCurrent.getNodeValue();
                if (sValue.trim().startsWith("Configuration changes saved on")) {
                    // overwrite message
                    nCurrent.setNodeValue(sbComment.toString());
                    bFound = true;
                }
            }
            nCurrent = nCurrent.getNextSibling();
        }
        if (!bFound) // no comment found: adding new
        {
            // create new comment node
            nComment = _oDomDocument.createComment(sbComment.toString());
            // insert comment before first node
            elRoot.insertBefore(nComment, elRoot.getFirstChild());
        }
        _oConfigHandler.saveConfiguration(_oDomDocument);
    } catch (ConfigurationException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error", e);
        throw new ConfigurationException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:Main.java

/**
 * Find all direct child elements of an element. Children which are
 * all-whitespace text nodes or comments are ignored; others cause an
 * exception to be thrown./*from  w  w  w .j  a va  2  s.com*/
 *
 * @param parent a parent element in a DOM tree
 * @return a list of direct child elements (may be empty)
 * @throws IllegalArgumentException if there are non-element children
 *                                  besides whitespace
 *
 * @since 8.4
 */
public static List<Element> findSubElements(Element parent) throws IllegalArgumentException {
    NodeList l = parent.getChildNodes();
    List<Element> elements = new ArrayList<Element>(l.getLength());
    for (int i = 0; i < l.getLength(); i++) {
        Node n = l.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            elements.add((Element) n);
        } else if (n.getNodeType() == Node.TEXT_NODE) {
            String text = ((Text) n).getNodeValue();
            if (text.trim().length() > 0) {
                throw new IllegalArgumentException("non-ws text encountered in " + parent + ": " + text); // NOI18N
            }
        } else if (n.getNodeType() == Node.COMMENT_NODE) {
            // OK, ignore
        } else {
            throw new IllegalArgumentException("unexpected non-element child of " + parent + ": " + n); // NOI18N
        }
    }
    return elements;
}

From source file:XMLDocumentWriter.java

/**
 * Output the specified DOM Node object, printing it using the specified
 * indentation string/* w  ww.ja  v  a 2s .com*/
 */
public void write(Node node, String indent) {
    // The output depends on the type of the node
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE: { // If its a Document node
        Document doc = (Document) node;
        out.println(indent + "<?xml version='1.0'?>"); // Output header
        Node child = doc.getFirstChild(); // Get the first node
        while (child != null) { // Loop 'till no more nodes
            write(child, indent); // Output node
            child = child.getNextSibling(); // Get next node
        }
        break;
    }
    case Node.DOCUMENT_TYPE_NODE: { // It is a <!DOCTYPE> tag
        DocumentType doctype = (DocumentType) node;
        // Note that the DOM Level 1 does not give us information about
        // the the public or system ids of the doctype, so we can't output
        // a complete <!DOCTYPE> tag here. We can do better with Level 2.
        out.println("<!DOCTYPE " + doctype.getName() + ">");
        break;
    }
    case Node.ELEMENT_NODE: { // Most nodes are Elements
        Element elt = (Element) node;
        out.print(indent + "<" + elt.getTagName()); // Begin start tag
        NamedNodeMap attrs = elt.getAttributes(); // Get attributes
        for (int i = 0; i < attrs.getLength(); i++) { // Loop through them
            Node a = attrs.item(i);
            out.print(" " + a.getNodeName() + "='" + // Print attr. name
                    fixup(a.getNodeValue()) + "'"); // Print attr. value
        }
        out.println(">"); // Finish start tag

        String newindent = indent + "    "; // Increase indent
        Node child = elt.getFirstChild(); // Get child
        while (child != null) { // Loop
            write(child, newindent); // Output child
            child = child.getNextSibling(); // Get next child
        }

        out.println(indent + "</" + // Output end tag
                elt.getTagName() + ">");
        break;
    }
    case Node.TEXT_NODE: { // Plain text node
        Text textNode = (Text) node;
        String text = textNode.getData().trim(); // Strip off space
        if ((text != null) && text.length() > 0) // If non-empty
            out.println(indent + fixup(text)); // print text
        break;
    }
    case Node.PROCESSING_INSTRUCTION_NODE: { // Handle PI nodes
        ProcessingInstruction pi = (ProcessingInstruction) node;
        out.println(indent + "<?" + pi.getTarget() + " " + pi.getData() + "?>");
        break;
    }
    case Node.ENTITY_REFERENCE_NODE: { // Handle entities
        out.println(indent + "&" + node.getNodeName() + ";");
        break;
    }
    case Node.CDATA_SECTION_NODE: { // Output CDATA sections
        CDATASection cdata = (CDATASection) node;
        // Careful! Don't put a CDATA section in the program itself!
        out.println(indent + "<" + "![CDATA[" + cdata.getData() + "]]" + ">");
        break;
    }
    case Node.COMMENT_NODE: { // Comments
        Comment c = (Comment) node;
        out.println(indent + "<!--" + c.getData() + "-->");
        break;
    }
    default: // Hopefully, this won't happen too much!
        System.err.println("Ignoring node: " + node.getClass().getName());
        break;
    }
}

From source file:com.marklogic.dom.DocumentImpl.java

/**
 * Check root node of a document to see if it conform to DOM Structure
 * Model. The root node can only be ELEMENT_NODE,
 * PROCESSING_INSTRUCTION_NODE or COMMENT_NODE.
 * /*from   w  ww .  jav a  2 s. c o m*/
 * @return 1(NON_XML) if root node violates DOM Structure Model; otherwise
 *         0(VALID_XML).
 */
private int getDocumentType() {
    NodeList children = getChildNodes();
    int elemCount = 0;
    for (int i = 0; i < children.getLength(); i++) {
        Node n = children.item(i);
        switch (n.getNodeType()) {
        case Node.ELEMENT_NODE:
            elemCount++;
            break;
        case Node.PROCESSING_INSTRUCTION_NODE:
        case Node.COMMENT_NODE:
            continue;
        default:
            return NON_XML;
        }
    }
    return elemCount <= 1 ? VALID_XML : NON_XML;
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.TextWriter.java

private void writeNode(Writer writer, Node node) throws IOException {
    short type = node.getNodeType();
    switch (type) {

    case Node.DOCUMENT_NODE:
        document(writer, (Document) node);
        break;/*from   w  ww  .j ava  2  s  .co m*/

    case Node.DOCUMENT_FRAGMENT_NODE:
        documentFragment(writer, (DocumentFragment) node);
        break;

    case Node.DOCUMENT_TYPE_NODE:
        documentType(writer, (DocumentType) node);
        break;

    case Node.ELEMENT_NODE:
        element(writer, (Element) node);
        break;

    case Node.ATTRIBUTE_NODE:
        attribute(writer, (Attr) node);
        break;

    case Node.ENTITY_REFERENCE_NODE:
        entityReference(writer, (EntityReference) node);
        break;

    case Node.ENTITY_NODE:
        entity(writer, (Entity) node);
        break;

    case Node.NOTATION_NODE:
        notation(writer, (Notation) node);
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        procInst(writer, (ProcessingInstruction) node);
        break;

    case Node.TEXT_NODE:
        text(writer, (Text) node);
        break;

    case Node.CDATA_SECTION_NODE:
        cDataSection(writer, (CDATASection) node);
        break;

    case Node.COMMENT_NODE:
        comment(writer, (Comment) node);
        break;
    }
}