Java Code Examples for org.w3c.dom.Node.getNodeType()

The following are Jave code examples for showing how to use getNodeType() of the org.w3c.dom.Node class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: generator_mybatis   File: MyBatisGeneratorConfigurationParser.java   View Source Code Vote up 7 votes
protected void parseConnectionFactory(Context context, Node node) {
    ConnectionFactoryConfiguration connectionFactoryConfiguration = new ConnectionFactoryConfiguration();

    context.setConnectionFactoryConfiguration(connectionFactoryConfiguration);

    Properties attributes = parseAttributes(node);
    String type = attributes.getProperty("type"); //$NON-NLS-1$

    if (stringHasValue(type)) {
        connectionFactoryConfiguration.setConfigurationType(type);
    }

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperty(connectionFactoryConfiguration, childNode);
        }
    }
}
 
Example 2
Project: openjdk-jdk10   File: KeyInfo.java   View Source Code Vote up 6 votes
/**
 * Method lengthUnknownElement
 * NOTE possibly buggy.
 * @return the number of the UnknownElement tags
 */
public int lengthUnknownElement() {
    int res = 0;
    NodeList nl = this.constructionElement.getChildNodes();

    for (int i = 0; i < nl.getLength(); i++) {
        Node current = nl.item(i);

        /**
         * $todo$ using this method, we don't see unknown Elements
         *  from Signature NS; revisit
         */
        if ((current.getNodeType() == Node.ELEMENT_NODE)
            && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
            res++;
        }
    }

    return res;
}
 
Example 3
Project: jdk8u-jdk   File: XMLUtils.java   View Source Code Vote up 6 votes
/**
 * Method getStrFromNode
 *
 * @param xpathnode
 * @return the string for the node.
 */
public static String getStrFromNode(Node xpathnode) {
    if (xpathnode.getNodeType() == Node.TEXT_NODE) {
        // we iterate over all siblings of the context node because eventually,
        // the text is "polluted" with pi's or comments
        StringBuilder sb = new StringBuilder();

        for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
            currentSibling != null;
            currentSibling = currentSibling.getNextSibling()) {
            if (currentSibling.getNodeType() == Node.TEXT_NODE) {
                sb.append(((Text) currentSibling).getData());
            }
        }

        return sb.toString();
    } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
        return ((Attr) xpathnode).getNodeValue();
    } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        return ((ProcessingInstruction) xpathnode).getNodeValue();
    }

    return null;
}
 
Example 4
Project: MybatisGeneatorUtil   File: MyBatisGeneratorConfigurationParser.java   View Source Code Vote up 6 votes
protected void parseConnectionFactory(Context context, Node node) {
    ConnectionFactoryConfiguration connectionFactoryConfiguration = new ConnectionFactoryConfiguration();

    context.setConnectionFactoryConfiguration(connectionFactoryConfiguration);

    Properties attributes = parseAttributes(node);
    String type = attributes.getProperty("type"); //$NON-NLS-1$

    if (stringHasValue(type)) {
        connectionFactoryConfiguration.setConfigurationType(type);
    }

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperty(connectionFactoryConfiguration, childNode);
        }
    }
}
 
Example 5
Project: OpenJSharp   File: DOMUtil.java   View Source Code Vote up 6 votes
/** Finds and returns the last child node with the given qualified name. */
public static Element getLastChildElementNS(Node parent,
        String[][] elemNames) {

    // search for node
    Node child = parent.getLastChild();
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            for (int i = 0; i < elemNames.length; i++) {
                String uri = child.getNamespaceURI();
                if (uri != null && uri.equals(elemNames[i][0]) &&
                        child.getLocalName().equals(elemNames[i][1])) {
                    return (Element)child;
                }
            }
        }
        child = child.getPreviousSibling();
    }

    // not found
    return null;

}
 
Example 6
Project: openjdk-jdk10   File: DOMStreamReader.java   View Source Code Vote up 6 votes
public int next() throws XMLStreamException {
    while(true) {
        int r = _next();
        switch (r) {
        case CHARACTERS:
            // if we are currently at text node, make sure that this is a meaningful text node.
            Node prev = _current.getPreviousSibling();
            if(prev!=null && prev.getNodeType()==Node.TEXT_NODE)
                continue;   // nope. this is just a continuation of previous text that should be invisible

            Text t = (Text)_current;
            wholeText = t.getWholeText();
            if(wholeText.length()==0)
                continue;   // nope. this is empty text.
            return CHARACTERS;
        case START_ELEMENT:
            splitAttributes();
            return START_ELEMENT;
        default:
            return r;
        }
    }
}
 
Example 7
Project: OpenJSharp   File: TreeWalkerImpl.java   View Source Code Vote up 5 votes
/** Internal function.
 *  Return the last child Node, from the input node
 *  after applying filter, whatToshow.
 *  The current node is not consulted or set.
 */
Node getLastChild(Node node) {

    if (node == null) return null;

    if ( !fEntityReferenceExpansion
         && node.getNodeType() == Node.ENTITY_REFERENCE_NODE)
        return null;

    Node newNode = node.getLastChild();
    if (newNode == null)  return null;

    int accept = acceptNode(newNode);

    if (accept == NodeFilter.FILTER_ACCEPT)
        return newNode;
    else
    if (accept == NodeFilter.FILTER_SKIP
        && newNode.hasChildNodes())
    {
        Node lChild = getLastChild(newNode);
        if (lChild == null) {
            return getPreviousSibling(newNode, node);
        }
        return lChild;
    }
    else
    //if (accept == NodeFilter.REJECT_NODE)
    {
        return getPreviousSibling(newNode, node);
    }


}
 
Example 8
Project: apache-tomcat-7.0.73-with-comment   File: DomUtil.java   View Source Code Vote up 5 votes
/** Get the first direct child with a given type
 */
public static Node getChild( Node parent, int type ) {
    Node n=parent.getFirstChild();
    while( n!=null && type != n.getNodeType() ) {
        n=n.getNextSibling();
    }
    if( n==null ) return null;
    return n;
}
 
Example 9
Project: OpenJSharp   File: KeyInfo.java   View Source Code Vote up 5 votes
/**
 * Searches the library wide KeyResolvers for Private keys
 *
 * @return the private key contained in this KeyInfo
 * @throws KeyResolverException
 */
PrivateKey getPrivateKeyFromStaticResolvers() throws KeyResolverException {
    Iterator<KeyResolverSpi> it = KeyResolver.iterator();
    while (it.hasNext()) {
        KeyResolverSpi keyResolver = it.next();
        keyResolver.setSecureValidation(secureValidation);

        Node currentChild = this.constructionElement.getFirstChild();
        String uri = this.getBaseURI();
        while (currentChild != null)      {
            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
                // not using StorageResolvers at the moment
                // since they cannot return private keys
                PrivateKey pk =
                    keyResolver.engineLookupAndResolvePrivateKey(
                        (Element) currentChild, uri, null
                    );

                if (pk != null) {
                    return pk;
                }
            }
            currentChild = currentChild.getNextSibling();
        }
    }
    return null;
}
 
Example 10
Project: Equella   File: DOMHelper.java   View Source Code Vote up 5 votes
/**
 * Retrieves the text value from a node's child text node.
 */
static String getValueForNode(Node node, String defaultValue)
{
	String value = null;
	if( node != null )
	{
		switch( node.getNodeType() )
		{
			case Node.ELEMENT_NODE: {
				Node textNode = node.getFirstChild();
				if( textNode != null )
				{
					value = textNode.getNodeValue();
				}
				break;
			}

			case Node.ATTRIBUTE_NODE: {
				value = node.getNodeValue();
				break;
			}

			default:
				break;
		}
	}

	if( value == null )
	{
		return defaultValue;
	}
	else
	{
		return value;
	}
}
 
Example 11
Project: Proyecto-DASI   File: ReadXMLTestSequence.java   View Source Code Vote up 5 votes
private String getVictimCoordinateZ(Element info, String tagcoordinate, String tagdimension){
      String valuez = "";        
NodeList coordinateNmElmntLst = info.getElementsByTagName(tagcoordinate);
Node coordinateNode = coordinateNmElmntLst.item(0);
if (coordinateNode.getNodeType() == Node.ELEMENT_NODE){
 Element coorInfo = (Element) coordinateNode;			  			  
 //Obtain information about y coordinate for the current victim 
 NodeList zNmElmntLst = coorInfo.getElementsByTagName(tagdimension);
 Element zNmElmnt = (Element) zNmElmntLst.item(0);
 NodeList zNm = zNmElmnt.getChildNodes();					  
 valuez = ((Node)zNm.item(0)).getNodeValue();				  
}
return valuez;
}
 
Example 12
Project: lazycat   File: DomUtil.java   View Source Code Vote up 5 votes
/**
 * Get the first direct child with a given type
 */
public static Node getChild(Node parent, int type) {
	Node n = parent.getFirstChild();
	while (n != null && type != n.getNodeType()) {
		n = n.getNextSibling();
	}
	if (n == null)
		return null;
	return n;
}
 
Example 13
Project: openjdk-jdk10   File: Bug6760982.java   View Source Code Vote up 5 votes
private static void _ProcessNode(Node n, int level) throws Exception {
    n.getAttributes();
    n.getChildNodes();

    // At this point, for JVM 1.6 and Xerces <= 1.3.1,
    // Test-XML.xml::mytest:Y's attribute is (already) bad.

    switch (n.getNodeType()) {

        case Node.TEXT_NODE:
            String str = n.getNodeValue().trim();

            /* ...Only print non-empty strings... */
            if (str.length() > 0) {
                String valStr = n.getNodeValue();

                _Println(valStr, level);
            }
            break;

        case Node.COMMENT_NODE:
            break;

        default: {
            String nodeNameStr = n.getNodeName();

            _Println(nodeNameStr + " (" + n.getClass() + "):", level);

            /* ...Print children... */
            _ProcessChildren(n, level);

            /* ...Print optional node attributes... */
            _PrintAttributes(n, level);
        }
    }
}
 
Example 14
Project: incubator-netbeans   File: DTDGrammarQueryProvider.java   View Source Code Vote up 5 votes
public Enumeration enabled(GrammarEnvironment ctx) {
    Enumeration en = ctx.getDocumentChildren();
    while (en.hasMoreElements()) {
        Node next = (Node) en.nextElement();
        if (next.getNodeType() == next.DOCUMENT_TYPE_NODE) {
            return org.openide.util.Enumerations.singleton (next);
        }
    }
    return null;
}
 
Example 15
Project: convertigo-engine   File: RemoveBlocks.java   View Source Code Vote up 5 votes
/**
 * Performs custom configuration for this database object.
 */
public void configure(Element element) throws Exception {
    super.configure(element);
    
    String version = element.getAttribute("version");
    
    if (version == null) {
        String s = XMLUtils.prettyPrintDOM(element);
        EngineException ee = new EngineException("Unable to find version number for the database object \"" + getName() + "\".\nXML data: " + s);
        throw ee;
    }

    if (VersionUtils.compare(version, "1.2.2") <= 0) {
        NodeList properties = element.getElementsByTagName("property");

        Element propValue = (Element) XMLUtils.findNodeByAttributeValue(properties, "name", "removeFields");

        Node xmlNode = null;
        NodeList nl = propValue.getChildNodes();
        int len_nl = nl.getLength();
        Boolean bRemoveFields = null;
        for (int j = 0 ; j < len_nl ; j++) {
            xmlNode = nl.item(j);
            if (xmlNode.getNodeType() == Node.ELEMENT_NODE) {
                bRemoveFields = (Boolean) XMLUtils.readObjectFromXml((Element) xmlNode);
                continue;
            }
        }

        setSelectionType((bRemoveFields == null) ? "[^(field)]" : (bRemoveFields.booleanValue() ? "" : "[^(field)]"));

        hasChanged = true;
        Engine.logBeans.warn("[RemoveBlocks] The object \"" + getName() + "\" has been updated to version 1.2.3");
    }
}
 
Example 16
Project: tomcat7   File: DomUtil.java   View Source Code Vote up 4 votes
/** Get the next sibling with the same name and type
 */
public static Node getNext( Node current ) {
    String name=current.getNodeName();
    int type=current.getNodeType();
    return getNext( current, name, type);
}
 
Example 17
Project: incubator-netbeans   File: AntBridge.java   View Source Code Vote up 4 votes
private static Map<String,Map<String,Class>> createCustomDefs(Map<String,ClassLoader> cDCLs) throws IOException {
    Map<String,Map<String,Class>> m = new HashMap<String,Map<String,Class>>();
    Map<String,Class> tasks = new HashMap<String,Class>();
    Map<String,Class> types = new HashMap<String,Class>();
    // XXX #36776: should eventually support <macrodef>s here
    m.put("task", tasks); // NOI18N
    m.put("type", types); // NOI18N
    for (Map.Entry<String,ClassLoader> entry : cDCLs.entrySet()) {
        String cnb = entry.getKey();
        ClassLoader l = entry.getValue();
        String resource = cnb.replace('.', '/') + "/antlib.xml"; // NOI18N
        URL antlib = l.getResource(resource);
        if (antlib == null) {
            throw new IOException("Could not find " + resource + " in ant/nblib/" + cnb.replace('.', '-') + ".jar"); // NOI18N
        }
        Document doc;
        try {
            doc = XMLUtil.parse(new InputSource(antlib.toExternalForm()), false, true, /*XXX needed?*/null, null);
        } catch (SAXException e) {
            throw (IOException)new IOException(e.toString()).initCause(e);
        }
        Element docEl = doc.getDocumentElement();
        if (!docEl.getLocalName().equals("antlib")) { // NOI18N
            throw new IOException("Bad root element for " + antlib + ": " + docEl); // NOI18N
        }
        NodeList nl = docEl.getChildNodes();
        Map<String,String> newTaskDefs = new HashMap<String,String>();
        Map<String,String> newTypeDefs = new HashMap<String,String>();
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            if (n.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            Element def = (Element)n;
            boolean type;
            if (def.getNodeName().equals("taskdef")) { // NOI18N
                type = false;
            } else if (def.getNodeName().equals("typedef")) { // NOI18N
                type = true;
            } else {
                LOG.warning("Warning: unrecognized definition " + def + " in " + antlib);
                continue;
            }
            String name = def.getAttribute("name"); // NOI18N
            if (name == null) {
                // Not a hard error since there might be e.g. <taskdef resource="..."/> here
                // which we do not parse but which is permitted in antlib by Ant.
                LOG.warning("Warning: skipping definition " + def + " with no 'name' in " + antlib);
                continue;
            }
            String classname = def.getAttribute("classname"); // NOI18N
            if (classname == null) {
                // But this is a hard error.
                throw new IOException("No 'classname' attr on def of " + name + " in " + antlib); // NOI18N
            }
            // XXX would be good to handle at least onerror attr too
            String nsname = "antlib:" + cnb + ":" + name; // NOI18N
            (type ? newTypeDefs : newTaskDefs).put(nsname, classname);
        }
        loadDefs(newTaskDefs, tasks, l);
        loadDefs(newTypeDefs, types, l);
    }
    return m;
}
 
Example 18
Project: openjdk-jdk10   File: DOMSerializerImpl.java   View Source Code Vote up 4 votes
private void prepareForSerialization(XMLSerializer ser, Node node) {
    ser.reset();
    ser.features = features;
    ser.fDOMErrorHandler = fErrorHandler;
    ser.fNamespaces = (features & NAMESPACES) != 0;
    ser.fNamespacePrefixes = (features & NSDECL) != 0;
    ser._format.setIndenting((features & PRETTY_PRINT) != 0);
    ser._format.setOmitComments((features & COMMENTS) == 0);
    ser._format.setOmitXMLDeclaration((features & XMLDECL) == 0);

    if ((features & WELLFORMED) != 0) {
        // REVISIT: this is inefficient implementation of well-formness. Instead, we should check
        // well-formness as we serialize the tree
        Node next, root;
        root = node;
        Method versionChanged;
        boolean verifyNames = true;
        Document document = (node.getNodeType() == Node.DOCUMENT_NODE)
                ? (Document) node
                : node.getOwnerDocument();
        try {
            versionChanged = document.getClass().getMethod("isXMLVersionChanged()", new Class[]{});
            if (versionChanged != null) {
                verifyNames = ((Boolean) versionChanged.invoke(document, (Object[]) null)).booleanValue();
            }
        } catch (Exception e) {
            //no way to test the version...
            //ignore the exception
        }
        if (node.getFirstChild() != null) {
            while (node != null) {
                verify(node, verifyNames, false);
                // Move down to first child
                next = node.getFirstChild();
                // No child nodes, so walk tree
                while (next == null) {
                    // Move to sibling if possible.
                    next = node.getNextSibling();
                    if (next == null) {
                        node = node.getParentNode();
                        if (root == node) {
                            next = null;
                            break;
                        }
                        next = node.getNextSibling();
                    }
                }
                node = next;
            }
        } else {
            verify(node, verifyNames, false);
        }
    }
}
 
Example 19
Project: OpenJSharp   File: DOMValidatorHelper.java   View Source Code Vote up 4 votes
/** Do processing for the start of a node. */
private void beginNode(Node node) {
    switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            fCurrentElement = node;
            // push namespace context
            fNamespaceContext.pushContext();
            // start element
            fillQName(fElementQName, node);
            processAttributes(node.getAttributes());
            fSchemaValidator.startElement(fElementQName, fAttributes, null);
            break;
        case Node.TEXT_NODE:
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.setIgnoringCharacters(true);
                sendCharactersToValidator(node.getNodeValue());
                fDOMValidatorHandler.setIgnoringCharacters(false);
                fDOMValidatorHandler.characters((Text) node);
            }
            else {
                sendCharactersToValidator(node.getNodeValue());
            }
            break;
        case Node.CDATA_SECTION_NODE:
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.setIgnoringCharacters(true);
                fSchemaValidator.startCDATA(null);
                sendCharactersToValidator(node.getNodeValue());
                fSchemaValidator.endCDATA(null);
                fDOMValidatorHandler.setIgnoringCharacters(false);
                fDOMValidatorHandler.cdata((CDATASection) node);
            }
            else {
                fSchemaValidator.startCDATA(null);
                sendCharactersToValidator(node.getNodeValue());
                fSchemaValidator.endCDATA(null);
            }
            break;
        case Node.PROCESSING_INSTRUCTION_NODE:
            /**
             * The validator does nothing with processing instructions so bypass it.
             * Send the ProcessingInstruction node directly to the result builder.
             */
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.processingInstruction((ProcessingInstruction) node);
            }
            break;
        case Node.COMMENT_NODE:
            /**
             * The validator does nothing with comments so bypass it.
             * Send the Comment node directly to the result builder.
             */
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.comment((Comment) node);
            }
            break;
        case Node.DOCUMENT_TYPE_NODE:
            /**
             * Send the DocumentType node directly to the result builder.
             */
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.doctypeDecl((DocumentType) node);
            }
            break;
        default: // Ignore other node types.
            break;
    }
}
 
Example 20
Project: OpenJSharp   File: OutputFormat.java   View Source Code Vote up 4 votes
/**
 * Determine the output method for the specified document.
 * If the document is an instance of {@link org.w3c.dom.html.HTMLDocument}
 * then the method is said to be <tt>html</tt>. If the root
 * element is 'html' and all text nodes preceding the root
 * element are all whitespace, then the method is said to be
 * <tt>html</tt>. Otherwise the method is <tt>xml</tt>.
 *
 * @param doc The document to check
 * @return The suitable method
 */
public static String whichMethod( Document doc )
{
    Node    node;
    String  value;
    int     i;

    // If document is derived from HTMLDocument then the default
    // method is html.
    if ( doc instanceof HTMLDocument )
        return Method.HTML;

    // Lookup the root element and the text nodes preceding it.
    // If root element is html and all text nodes contain whitespace
    // only, the method is html.

    // FIXME (SM) should we care about namespaces here?

    node = doc.getFirstChild();
    while (node != null) {
        // If the root element is html, the method is html.
        if ( node.getNodeType() == Node.ELEMENT_NODE ) {
            if ( node.getNodeName().equalsIgnoreCase( "html" ) ) {
                return Method.HTML;
            } else if ( node.getNodeName().equalsIgnoreCase( "root" ) ) {
                return Method.FOP;
            } else {
                return Method.XML;
            }
        } else if ( node.getNodeType() == Node.TEXT_NODE ) {
            // If a text node preceding the root element contains
            // only whitespace, this might be html, otherwise it's
            // definitely xml.
            value = node.getNodeValue();
            for ( i = 0 ; i < value.length() ; ++i )
                if ( value.charAt( i ) != 0x20 && value.charAt( i ) != 0x0A &&
                     value.charAt( i ) != 0x09 && value.charAt( i ) != 0x0D )
                    return Method.XML;
        }
        node = node.getNextSibling();
    }
    // Anything else, the method is xml.
    return Method.XML;
}