Java Code Examples for org.w3c.dom.Node#hasChildNodes()

The following examples show how to use org.w3c.dom.Node#hasChildNodes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DomUtil.java    From tool.accelerate.core with Apache License 2.0 6 votes vote down vote up
/**
 * Get all matching child nodes
 * @param parentNode - the parent node
 * @param name - name of child node to match 
 * @param value - value of child node to match, specify null to not match value
 * @return matching child nodes
 */
private static List<Node> getChildren(Node parentNode, String name, String value){
        List<Node> childNodes = new ArrayList<Node>();
        if(parentNode == null || name == null){
                return childNodes;
        }

        if (parentNode.getNodeType() == Node.ELEMENT_NODE && parentNode.hasChildNodes()) {
                NodeList children = parentNode.getChildNodes();
                for(int i=0; i < children.getLength(); i++){
                        Node child = children.item(i);
                        if(child != null && name.equals(child.getNodeName()) && (value == null || value.equals(child.getTextContent()))){
                                childNodes.add(child);
                        }
                }
        }

        return childNodes;
}
 
Example 2
Source File: AbstractTestCase.java    From marklogic-contentpump with Apache License 2.0 6 votes vote down vote up
protected void walkDOMAttr(NodeList nodes, Set<String> sb) {
    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            if (LOG.isDebugEnabled())
                LOG.debug(n.getNodeName());
        }
        if (n.hasAttributes()) {
            NamedNodeMap nnMap = n.getAttributes();
            for (int j = 0; j < nnMap.getLength(); j++) {
                Attr attr = (Attr) nnMap.item(j);
                String tmp = n.getNodeName() + "@" + attr.getName() + "="
                    + attr.getValue().replaceAll("\\s+", "");
                tmp += "#parent is " + attr.getParentNode();
                tmp += "#nextSibling is " + attr.getNextSibling();
                if (LOG.isDebugEnabled())
                    LOG.debug(tmp);
                sb.add(tmp);
            }
        }
        if (n.hasChildNodes()) {
            walkDOMAttr(n.getChildNodes(), sb);
        }
    }
}
 
Example 3
Source File: MybatisFragment.java    From hasor with Apache License 2.0 6 votes vote down vote up
private void parseNodeList(SqlNode sqlNode, NodeList nodeList) {
    for (int i = 0, len = nodeList.getLength(); i < len; i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.TEXT_NODE) {
            sqlNode.addChildNode(new TextSqlNode(node.getNodeValue().trim()));
        } else if (node.getNodeType() != Node.COMMENT_NODE) {
            String nodeName = node.getNodeName();
            SqlNode childNode;
            if ("foreach".equalsIgnoreCase(nodeName)) {
                childNode = parseForeachSqlNode(node);
            } else if ("if".equalsIgnoreCase(nodeName)) {
                childNode = new IfSqlNode(getNodeAttributeValue(node, "test"));
            } else {
                throw new UnsupportedOperationException("Unsupported tags :" + nodeName);
            }
            sqlNode.addChildNode(childNode);
            if (node.hasChildNodes()) {
                parseNodeList(childNode, node.getChildNodes());
            }
        }
    }
}
 
Example 4
Source File: ScriptValuesHelp.java    From hop with Apache License 2.0 5 votes vote down vote up
public String getSample( String strFunctionName, String strFunctionNameWithArgs ) {
  String sRC = "// Sorry, no Script available for " + strFunctionNameWithArgs;

  NodeList nl = dom.getElementsByTagName( "jsFunction" );
  for ( int i = 0; i < nl.getLength(); i++ ) {
    if ( nl.item( i ).getAttributes().getNamedItem( "name" ).getNodeValue().equals( strFunctionName ) ) {
      Node elSample = ( (Element) nl.item( i ) ).getElementsByTagName( "sample" ).item( 0 );
      if ( elSample.hasChildNodes() ) {
        return ( elSample.getFirstChild().getNodeValue() );
      }
    }
  }
  return sRC;
}
 
Example 5
Source File: SessionUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static List<String> getAttributeValue(Element token, String attributeNameSuffix) throws TechnicalConnectorException {
   NodeList attributes = extractAttributes(token);
   List<String> result = new ArrayList();
   if (attributes != null) {
      for(int i = 0; i < attributes.getLength(); ++i) {
         Node node = attributes.item(i);
         String attributeName = node.getAttributes().getNamedItem("AttributeName").getTextContent();
         String attributeNamespace = node.getAttributes().getNamedItem("AttributeNamespace").getTextContent();
         if (attributeName.matches(attributeNameSuffix) && attributeNamespace.equals("urn:be:fgov:certified-namespace:ehealth")) {
            if (node.hasChildNodes()) {
               NodeList attributeValueNodeList = node.getChildNodes();

               for(int index = 0; index < attributeValueNodeList.getLength(); ++index) {
                  result.add(attributeValueNodeList.item(index).getTextContent().trim());
               }
            } else {
               result.add(node.getTextContent().trim());
            }
         }
      }
   }

   if (result.isEmpty()) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.INVALID_TOKEN, new Object[]{"Token doesn't contain an attribute with " + attributeNameSuffix + " in namespace " + "urn:be:fgov:certified-namespace:ehealth"});
   } else {
      return result;
   }
}
 
Example 6
Source File: DTMNodeProxy.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param listVector
 * @param tempNode
 * @param tagname
 * @param isTagNameWildCard
 *
 *
 * Private method to be used for recursive iterations to obtain elements by tag name.
 */
private final void traverseChildren
(
  Vector listVector,
  Node tempNode,
  String tagname,
  boolean isTagNameWildCard) {
  if (tempNode == null)
  {
    return;
  }
  else
  {
    if (tempNode.getNodeType() == DTM.ELEMENT_NODE
          && (isTagNameWildCard || tempNode.getNodeName().equals(tagname)))
    {
      listVector.add(tempNode);
    }
    if(tempNode.hasChildNodes())
    {
      NodeList nodeList = tempNode.getChildNodes();
      for (int i = 0; i < nodeList.getLength(); i++)
      {
        traverseChildren(listVector, nodeList.item(i), tagname,
                         isTagNameWildCard);
      }
    }
  }
}
 
Example 7
Source File: DOM2DTM.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/** Utility function: Given a DOM Text node, determine whether it is
 * logically followed by another Text or CDATASection node. This may
 * involve traversing into Entity References.
 *
 * %REVIEW% DOM Level 3 is expected to add functionality which may
 * allow us to retire this.
 */
private Node logicalNextDOMTextNode(Node n)
{
      Node p=n.getNextSibling();
      if(p==null)
      {
              // Walk out of any EntityReferenceNodes that ended with text
              for(n=n.getParentNode();
                      n!=null && ENTITY_REFERENCE_NODE == n.getNodeType();
                      n=n.getParentNode())
              {
                      p=n.getNextSibling();
                      if(p!=null)
                              break;
              }
      }
      n=p;
      while(n!=null && ENTITY_REFERENCE_NODE == n.getNodeType())
      {
              // Walk into any EntityReferenceNodes that start with text
              if(n.hasChildNodes())
                      n=n.getFirstChild();
              else
                      n=n.getNextSibling();
      }
      if(n!=null)
      {
              // Found a logical next sibling. Is it text?
              int ntype=n.getNodeType();
              if(TEXT_NODE != ntype && CDATA_SECTION_NODE != ntype)
                      n=null;
      }
      return n;
}
 
Example 8
Source File: Blackboard6FileParser.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public String getType(Node resourceNode) {
	
	String nodeType = XPathHelper.getNodeValue("./@type", resourceNode);
	
	if ("resource/x-bb-document".equals(nodeType)) {
		/*
		 * Since we've gotten a bb-document, we need to figure out what kind it is. Known possible are:
		 *   1. x-bb-externallink
		 *   2. x-bb-document
		 *     a. Plain text
		 *     b. Smart text
		 *     c. HTML
		 * The reason we have to do this is that all the above types are listed as type "resource/x-bb-document"
		 *  in the top level resource node. Their true nature is found with the XML descriptor (.dat file) 
		 */
		
		if(resourceNode.hasChildNodes()) {
			// If it has child-nodes (files, usually) we don't want to parse the actual document
			return nodeType;
		}
		
		String subType = XPathHelper.getNodeValue("/CONTENT/CONTENTHANDLER/@value", resourceHelper.getDescriptor(resourceNode));	
		if ("resource/x-bb-externallink".equals(subType)) {
			nodeType = "resource/x-bb-externallink";
		} else if ("resource/x-bb-asmt-test-link".equals(subType)) {
			nodeType = "resource/x-bb-asmt-test-link";
		} else {
			String docType = XPathHelper.getNodeValue("/CONTENT/BODY/TYPE/@value", resourceHelper.getDescriptor(resourceNode));
			if ("H".equals(docType)) {
				nodeType = "resource/x-bb-document-html";
			} else if ("P".equals(docType)) {
				nodeType = "resource/x-bb-document-plain-text";
			} else if ("S".equals(docType)) {
				nodeType = "resource/x-bb-document-smart-text";
			}
		}
	}
	
	return nodeType;
}
 
Example 9
Source File: ScriptValuesHelp.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public String getSample( String strFunctionName, String strFunctionNameWithArgs ) {
  String sRC = "// Sorry, no Script available for " + strFunctionNameWithArgs;

  NodeList nl = dom.getElementsByTagName( "jsFunction" );
  for ( int i = 0; i < nl.getLength(); i++ ) {
    if ( nl.item( i ).getAttributes().getNamedItem( "name" ).getNodeValue().equals( strFunctionName ) ) {
      Node elSample = ( (Element) nl.item( i ) ).getElementsByTagName( "sample" ).item( 0 );
      if ( elSample.hasChildNodes() ) {
        return ( elSample.getFirstChild().getNodeValue() );
      }
    }
  }
  return sRC;
}
 
Example 10
Source File: ManifestAttributes.java    From Box with Apache License 2.0 5 votes vote down vote up
private void parse(Document doc) {
	NodeList nodeList = doc.getChildNodes();
	for (int count = 0; count < nodeList.getLength(); count++) {
		Node node = nodeList.item(count);
		if (node.getNodeType() == Node.ELEMENT_NODE
				&& node.hasChildNodes()) {
			parseAttrList(node.getChildNodes());
		}
	}
}
 
Example 11
Source File: DTMNodeProxy.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param listVector
 * @param tempNode
 * @param namespaceURI
 * @param localname
 * @param isNamespaceURIWildCard
 * @param isLocalNameWildCard
 *
 * Private method to be used for recursive iterations to obtain elements by tag name
 * and namespaceURI.
 */
private final void traverseChildren
(
 Vector listVector,
 Node tempNode,
 String namespaceURI,
 String localname,
 boolean isNamespaceURIWildCard,
 boolean isLocalNameWildCard)
 {
  if (tempNode == null)
  {
    return;
  }
  else
  {
    if (tempNode.getNodeType() == DTM.ELEMENT_NODE
            && (isLocalNameWildCard
                    || tempNode.getLocalName().equals(localname)))
    {
      String nsURI = tempNode.getNamespaceURI();
      if ((namespaceURI == null && nsURI == null)
             || isNamespaceURIWildCard
             || (namespaceURI != null && namespaceURI.equals(nsURI)))
      {
        listVector.add(tempNode);
      }
    }
    if(tempNode.hasChildNodes())
    {
      NodeList nl = tempNode.getChildNodes();
      for(int i = 0; i < nl.getLength(); i++)
      {
        traverseChildren(listVector, nl.item(i), namespaceURI, localname,
                         isNamespaceURIWildCard, isLocalNameWildCard);
      }
    }
  }
}
 
Example 12
Source File: XmlConfigFactory.java    From Octopus with MIT License 5 votes vote down vote up
private FormatterContainer readFormatter(Node formatNode) {
    DefaultFormatterContainer container = new DefaultFormatterContainer();

    String dateFormat = getAttribute(formatNode, XmlNode.Formatters.Attribute.DATE_FORMAT);
    if (StringUtils.isEmpty(dateFormat)) {
        container.addFormat(Date.class, new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    } else {
        container.addFormat(Date.class, new DateFormatter(dateFormat));
    }

    if (formatNode != null && formatNode.hasChildNodes()) {
        NodeList children = formatNode.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node item = children.item(i);
            if (item.getNodeType() == Node.ELEMENT_NODE || !item.getNodeName().equals(XmlNode.Formatters.Formatter.nodeName)) {
                continue;
            }
            String targetClass = getAttribute(item, XmlNode.Formatters.Formatter.Attribute.TARGET);
            String formatClass = getAttribute(item, XmlNode.Formatters.Formatter.Attribute.CLASS);

            try {
                Class target = Class.forName(targetClass);
                Class format = Class.forName(formatClass);
                container.addFormat(target, (cn.chenhuanming.octopus.formatter.Formatter) format.newInstance());
            } catch (Exception e) {
                throw new IllegalArgumentException(e);
            }

        }
    }
    return container;
}
 
Example 13
Source File: DTMNodeProxy.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param listVector
 * @param tempNode
 * @param tagname
 * @param isTagNameWildCard
 *
 *
 * Private method to be used for recursive iterations to obtain elements by tag name.
 */
private final void traverseChildren
(
  Vector listVector,
  Node tempNode,
  String tagname,
  boolean isTagNameWildCard) {
  if (tempNode == null)
  {
    return;
  }
  else
  {
    if (tempNode.getNodeType() == DTM.ELEMENT_NODE
          && (isTagNameWildCard || tempNode.getNodeName().equals(tagname)))
    {
      listVector.add(tempNode);
    }
    if(tempNode.hasChildNodes())
    {
      NodeList nodeList = tempNode.getChildNodes();
      for (int i = 0; i < nodeList.getLength(); i++)
      {
        traverseChildren(listVector, nodeList.item(i), tagname,
                         isTagNameWildCard);
      }
    }
  }
}
 
Example 14
Source File: AbstractXTeeBaseEndpoint.java    From j-road with Apache License 2.0 5 votes vote down vote up
private void copyParing(Document paring, Node response) throws Exception {
  Node paringElement = response.appendChild(response.getOwnerDocument().createElement("paring"));
  Node kehaNode = response.getOwnerDocument().importNode(paring.getDocumentElement(), true);

  NamedNodeMap attrs = kehaNode.getAttributes();
  for (int i = 0; i < attrs.getLength(); i++) {
    paringElement.getAttributes().setNamedItem(attrs.item(i).cloneNode(true));
  }

  while (kehaNode.hasChildNodes()) {
    paringElement.appendChild(kehaNode.getFirstChild());
  }
}
 
Example 15
Source File: TIFFImageMetadata.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private Node getChildNode(Node node, String childName) {
    Node childNode = null;
    if(node.hasChildNodes()) {
        NodeList childNodes = node.getChildNodes();
        int length = childNodes.getLength();
        for(int i = 0; i < length; i++) {
            Node item = childNodes.item(i);
            if(item.getNodeName().equals(childName)) {
                childNode = item;
                break;
            }
        }
    }
    return childNode;
}
 
Example 16
Source File: WSDL11SOAPOperationExtractor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private void isComplexTypeContainsArray(Node current) {
    if (current.getAttributes() != null && isArrayType(current)) {
        isArrayType = true;
    } else if (current.hasChildNodes()) {
        NodeList nodeList = current.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node child = nodeList.item(i);
            isComplexTypeContainsArray(child);
        }
    }
}
 
Example 17
Source File: MessageParser.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 遍历节点 node 以过滤所有的 html 标签.
 * @param node
 *            要遍历的节点
 */
private void processNode(Node node) {
	if (node == null) {
		return;
	}
	if ("BR".equals(node.getNodeName())) {
		textBuffer.append("\n" + newLine(node));
	} else if ("TR".equals(node.getNodeName())) {
		textBuffer.append("\n" + newLine(node));
	} else if ("DIV".equals(node.getNodeName())) {
		textBuffer.append("\n" + newLine(node));
	} else if ("BLOCKQUOTE".equals(node.getNodeName())) {
		if (node.getAttributes() != null) {
			Node item = node.getAttributes().getNamedItem("type");
			if (item != null) {
				if ("cite".equalsIgnoreCase(item.getNodeValue())) {
					textBuffer.append("\n" + newLine(node));
				}
			}
		}
	} else if ("LI".equals(node.getNodeName())) {
		textBuffer.append("\n" + newLine(node) + "    ");
	}
	if (node.getNodeType() == Node.TEXT_NODE) {
		String value = node.getNodeValue();
		if (value != null) {
			if (value.indexOf("\n") != -1 && "".equals(value.trim())) {
				return;
			} else if (value.indexOf("\n") != -1) {
				if (!"BODY".equals(node.getParentNode().getNodeName())) {
					value = value.replaceAll("\n", "");
				}
			}
		}
		textBuffer.append(value);
	} else if (node.hasChildNodes()) {
		NodeList childList = node.getChildNodes();
		int childLen = childList.getLength();

		for (int count = 0; count < childLen; count++) {
			processNode(childList.item(count));
		}
	} else {
		return;
	}
}
 
Example 18
Source File: JFIFMarkerSegment.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Updates the data in this object from the given DOM Node tree.
 * If fromScratch is true, this object is being constructed.
 * Otherwise an existing object is being modified.
 * Throws an IIOInvalidTreeException if the tree is invalid in
 * any way.
 */
void updateFromNativeNode(Node node, boolean fromScratch)
    throws IIOInvalidTreeException {
    // none of the attributes are required
    NamedNodeMap attrs = node.getAttributes();
    if (attrs.getLength() > 0) {
        int value = getAttributeValue(node, attrs, "majorVersion",
                                      0, 255, false);
        majorVersion = (value != -1) ? value : majorVersion;
        value = getAttributeValue(node, attrs, "minorVersion",
                                  0, 255, false);
        minorVersion = (value != -1) ? value : minorVersion;
        value = getAttributeValue(node, attrs, "resUnits", 0, 2, false);
        resUnits = (value != -1) ? value : resUnits;
        value = getAttributeValue(node, attrs, "Xdensity", 1, 65535, false);
        Xdensity = (value != -1) ? value : Xdensity;
        value = getAttributeValue(node, attrs, "Ydensity", 1, 65535, false);
        Ydensity = (value != -1) ? value : Ydensity;
        value = getAttributeValue(node, attrs, "thumbWidth", 0, 255, false);
        thumbWidth = (value != -1) ? value : thumbWidth;
        value = getAttributeValue(node, attrs, "thumbHeight", 0, 255, false);
        thumbHeight = (value != -1) ? value : thumbHeight;
    }
    if (node.hasChildNodes()) {
        NodeList children = node.getChildNodes();
        int count = children.getLength();
        if (count > 2) {
            throw new IIOInvalidTreeException
                ("app0JFIF node cannot have > 2 children", node);
        }
        for (int i = 0; i < count; i++) {
            Node child = children.item(i);
            String name = child.getNodeName();
            if (name.equals("JFXX")) {
                if ((!extSegments.isEmpty()) && fromScratch) {
                    throw new IIOInvalidTreeException
                        ("app0JFIF node cannot have > 1 JFXX node", node);
                }
                NodeList exts = child.getChildNodes();
                int extCount = exts.getLength();
                for (int j = 0; j < extCount; j++) {
                    Node ext = exts.item(j);
                    extSegments.add(new JFIFExtensionMarkerSegment(ext));
                }
            }
            if (name.equals("app2ICC")) {
                if ((iccSegment != null) && fromScratch) {
                    throw new IIOInvalidTreeException
                        ("> 1 ICC APP2 Marker Segment not supported", node);
                }
                iccSegment = new ICCMarkerSegment(child);
            }
        }
    }
}
 
Example 19
Source File: XMLCipher.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Removes the contents of a <code>Node</code>.
 *
 * @param node the <code>Node</code> to clear.
 */
private static void removeContent(Node node) {
    while (node.hasChildNodes()) {
        node.removeChild(node.getFirstChild());
    }
}
 
Example 20
Source File: XMLUtil.java    From seleniumtestsframework with Apache License 2.0 3 votes vote down vote up
/**
 * Gets Nodes identical to a given test Node for a given parent Node
 */

public static List getSimilarChildNodes(Node parent, Node testNode, boolean ignoreWhitespace)

{

    ArrayList nodes = new ArrayList();


    if (!parent.hasChildNodes())

        return nodes;


    NodeList childNodes = parent.getChildNodes();


    for (int i = 0; i < childNodes.getLength(); i++)

    {

        if (nodesSimilar(childNodes.item(i), testNode, ignoreWhitespace))

            nodes.add(childNodes.item(i));

    }


    return nodes;

}