Java Code Examples for org.w3c.dom.NodeList#getLength()

The following examples show how to use org.w3c.dom.NodeList#getLength() . These examples are extracted from open source projects. 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
private static boolean isNewFormatNode(Node node) {
    // check for new node format - if the first non-whitespace node
    // is an XML comment, and the comment includes
    // one of the old element tags,
    // then it is a generated node
    NodeList children = node.getChildNodes();
    int length = children.getLength();
    for (int i = 0; i < length; i++) {
        Node childNode = children.item(i);
        if (childNode != null && childNode.getNodeType() == Node.COMMENT_NODE) {
            String commentData = ((Comment) childNode).getData();
            return MergeConstants.comentContainsTag(commentData);
        }
    }
    
    return false;
}
 
Example 2
/** Constructs a <code>UUIDListBox</code> based on the provided
   *  <code>org.w3c.dom.Node</code>.
   */
  public XMLBox(Node node) throws IIOInvalidTreeException {
      super(node);
      NodeList children = node.getChildNodes();

      for (int i = 0; i < children.getLength(); i++) {
          Node child = children.item(i);
          String name = child.getNodeName();

          if ("Content".equals(name)) {
String value = child.getNodeValue();
if (value != null)
    data = value.getBytes();
else if (child instanceof IIOMetadataNode) {
    value = (String)((IIOMetadataNode)child).getUserObject();
    if (value != null)
	data = value.getBytes();
}
          }
      }
  }
 
Example 3
Source Project: arcusplatform   File: TypeReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected TypeDefinition buildModel(Element root) {
   TypeDefinitionBuilder builder = builder();
   builder
      .withName(root.getAttribute("name"))
      .withVersion(root.getAttribute("version"));
   
   NodeList nodes = root.getElementsByTagNameNS(schemaURI, "description");
   if (nodes.getLength() > 0)
   {
      Element description = (Element)nodes.item(0);
      builder.withDescription(readDescription(description));
   }
   else {
      logger.warn("No description was given for the struct {}", root.getAttribute("name"));
   }
   
   builder.withAttributes(buildAttributes(root.getElementsByTagNameNS(schemaURI, "attribute")));
   return builder.build();
}
 
Example 4
/**
 * The math:highest function returns the nodes in the node set whose value is the maximum
 * value for the node set. The maximum value for the node set is the same as the value as
 * calculated by math:max. A node has this maximum value if the result of converting its
 * string value to a number as if by the number function is equal to the maximum value,
 * where the equality comparison is defined as a numerical comparison using the = operator.
 * <p>
 * If any of the nodes in the node set has a non-numeric value, the math:max function will
 * return NaN. The definition numeric comparisons entails that NaN != NaN. Therefore if any
 * of the nodes in the node set has a non-numeric value, math:highest will return an empty
 * node set.
 *
 * @param nl The NodeList for the node-set to be evaluated.
 *
 * @return node-set with nodes containing the maximum value found, an empty node-set
 * if any node cannot be converted to a number.
 */
public static NodeList highest (NodeList nl)
{
  double maxValue = max(nl);

  NodeSet highNodes = new NodeSet();
  highNodes.setShouldCacheNodes(true);

  if (Double.isNaN(maxValue))
    return highNodes;  // empty Nodeset

  for (int i = 0; i < nl.getLength(); i++)
  {
    Node n = nl.item(i);
    double d = toNumber(n);
    if (d == maxValue)
      highNodes.addElement(n);
  }
  return highNodes;
}
 
Example 5
private static void parseNested(Element element, ParserContext parserContext, Class<?> beanClass, boolean required, String tag, String property, String ref, BeanDefinition beanDefinition) {
    NodeList nodeList = element.getChildNodes();
    if (nodeList != null && nodeList.getLength() > 0) {
        boolean first = true;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                if (tag.equals(node.getNodeName())
                        || tag.equals(node.getLocalName())) {
                    if (first) {
                        first = false;
                        String isDefault = element.getAttribute("default");
                        if (isDefault == null || isDefault.length() == 0) {
                            beanDefinition.getPropertyValues().addPropertyValue("default", "false");
                        }
                    }
                    BeanDefinition subDefinition = parse((Element) node, parserContext, beanClass, required);
                    if (subDefinition != null && ref != null && ref.length() > 0) {
                        subDefinition.getPropertyValues().addPropertyValue(property, new RuntimeBeanReference(ref));
                    }
                }
            }
        }
    }
}
 
Example 6
Source Project: das   File: DalConfigureFactory.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, String> getSettings(Node pNode) {
    Map<String, String> settings = new HashMap<>();

    if (pNode == null) {
        return settings;
    }

    Node settingsNode = getChildNode(pNode, SETTINGS);

    if (settingsNode != null) {
        NodeList children = settingsNode.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
                settings.put(children.item(i).getNodeName(), children.item(i).getTextContent().trim());
            }
        }
    }
    return settings;
}
 
Example 7
@Override
protected void loadCustomXmlData(Element payloadNode) {
	NodeList bodyTemplateElements = payloadNode.getElementsByTagName("BodyTemplate");
	if (bodyTemplateElements.getLength() > 0) {
		NodeList bodyNodes = bodyTemplateElements.item(0).getChildNodes();
		for (int i = 0; i < bodyNodes.getLength(); i++) {
			if (bodyNodes.item(i) instanceof CharacterData) {
				CharacterData data = (CharacterData) bodyNodes.item(i);
				mBodyTemplate = data.getData();
				break;
			}
		}
	}

	setName(getNodeValue(payloadNode, "TemplateName"));
}
 
Example 8
public void loadfromXML(final @Nonnull Element xmlElement) {

    setDifferentiateMSn(Boolean.valueOf(xmlElement.getAttribute(DIFFMSN_ELEMENT)));

    final NodeList nodes = xmlElement.getElementsByTagName(WRAPPER_ELEMENT);
    final int nodesLength = nodes.getLength();

    for (int i = 0; i < nodesLength; i++) {
      final Element queueElement = (Element) nodes.item(i);
      final String levelName = queueElement.getAttribute(MSLEVEL_ELEMENT);

      for (MSLevel mslevel : MSLevel.cropValues()) {
        if (levelName.equals(MSLEVEL_VALUE_ELEMENT[mslevel.ordinal()])) {
          queues[mslevel.ordinal()] = DataPointProcessingQueue.loadfromXML(queueElement);
        }
      }
    }
  }
 
Example 9
Source Project: mzmine3   File: XMLUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static Range<Integer> parseIntegerRange(Element xmlElement, String tagName) {
  NodeList items = xmlElement.getElementsByTagName(tagName);
  if (items.getLength() == 0)
    return null;
  Element tag = (Element) items.item(0);
  items = tag.getElementsByTagName("min");
  if (items.getLength() == 0)
    return null;
  Element min = (Element) items.item(0);
  items = tag.getElementsByTagName("max");
  if (items.getLength() == 0)
    return null;
  Element max = (Element) items.item(0);

  String minText = min.getTextContent();
  String maxText = max.getTextContent();
  Range<Integer> r = Range.closed(Integer.valueOf(minText), Integer.valueOf(maxText));
  return r;
}
 
Example 10
Source Project: ns4_frame   File: XMLUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 为了实现中文与其他字符的转换,加了一个映射字段map(key,value) key为简体中文value为要转换的文字,如果不需要转换那么赋值null即可
 *
 **/
public static String getText(Element e, Map<String,String> map) {
	NodeList nl = e.getChildNodes();
	int max = nl.getLength();
	for (int i = 0; i < max; i++) {
		Node n = nl.item(i);
		if (n.getNodeType() == Node.TEXT_NODE) {
			String value = n.getNodeValue();
			if(value != null && value.trim().length() != 0 && map != null && !map.isEmpty() && map.containsKey(value.trim())){
				value = map.get(value.trim());
			}
			return value;
		}
	}
	return "";
}
 
Example 11
private List<ErrorCodeDefinition> buildErrorCodes(NodeList nodes) {
   List<ErrorCodeDefinition> errorCodes = new ArrayList<ErrorCodeDefinition>(nodes.getLength() + 1);
   for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element)nodes.item(i);
      ErrorCodeDefinition errorCode = readErrorCode(element);
      errorCodes.add(errorCode);
      logger.trace("Added errorCode [{}]", errorCode.getName());
   }
   return errorCodes;
}
 
Example 12
private String extractText(Element element) {
   NodeList children = element.getChildNodes();
   if (children != null && children.getLength() > 0) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < children.getLength(); i++) {
         Node child = children.item(i);
         if (child instanceof Text) {
            sb.append(((Text)child).getNodeValue());
         }
      }
      return sb.toString().trim();
   }
   return null;
}
 
Example 13
DHTMarkerSegment(Node node) throws IIOInvalidTreeException {
    super(JPEG.DHT);
    NodeList children = node.getChildNodes();
    int size = children.getLength();
    if ((size < 1) || (size > 4)) {
        throw new IIOInvalidTreeException("Invalid DHT node", node);
    }
    for (int i = 0; i < size; i++) {
        tables.add(new Htable(children.item(i)));
    }
}
 
Example 14
/**
 * Parse a set element.
 */
public Set<Object> parseSetElement(Element collectionEle, @Nullable BeanDefinition bd) {
	String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
	NodeList nl = collectionEle.getChildNodes();
	ManagedSet<Object> target = new ManagedSet<>(nl.getLength());
	target.setSource(extractSource(collectionEle));
	target.setElementTypeName(defaultElementType);
	target.setMergeEnabled(parseMergeAttribute(collectionEle));
	parseCollectionElements(nl, target, bd, defaultElementType);
	return target;
}
 
Example 15
@Override
public void loadValueFromXML(Element xmlElement) {
  NodeList items = xmlElement.getElementsByTagName("item");
  ArrayList<LipidModification> newValues = new ArrayList<>();
  for (int i = 0; i < items.getLength(); i++) {
    String itemString = items.item(i).getTextContent();
    for (int j = 0; j < choices.length; j++) {
      if (choices[j].toString().equals(itemString)) {
        newValues.add(choices[j]);
      }
    }
  }
  this.values = newValues.toArray(new LipidModification[0]);
}
 
Example 16
private void writeXmlFormatted(Document pom, File destination) throws Exception {
    XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyNodes = (NodeList) xpath.evaluate(pom, XPathConstants.NODESET);

    // Remove empty text nodes
    for (int i = 0; i < emptyNodes.getLength(); i++) {
        Node emptyNode = emptyNodes.item(i);
        emptyNode.getParentNode().removeChild(emptyNode);
    }

    pom.setXmlStandalone(true);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    DOMSource source = new DOMSource(pom);

    String content;
    try (StringWriter out = new StringWriter()) {
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        content = out.toString();
    }

    // Fix header formatting problem
    content = content.replaceFirst("-->", "-->\n").replaceFirst("\\?><!--", "\\?>\n<!--");

    writeIfChanged(content, destination);
}
 
Example 17
protected void deserializeCommentElement(Element aElement, ModelItem aItem) {
	NodeList theChildren = aElement.getChildNodes();
	for (int i = 0; i < theChildren.getLength(); i++) {
		Node theChild = theChildren.item(i);
		if (COMMENT.equals(theChild.getNodeName())) {
			Element theElement = (Element) theChild;
			if (theElement.getChildNodes().getLength() > 0) {
				aItem.setComment(theElement.getChildNodes().item(0).getNodeValue());
			}
		}
	}
}
 
Example 18
Source Project: micro-integrator   File: DBUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static List<Node> getNodesAsList(Element element) {
	List<Node> nodes = new ArrayList<Node>();
	NodeList nodeList = element.getChildNodes();
	int count = nodeList.getLength();
	for (int i = 0; i < count; i++) {
		nodes.add(nodeList.item(i));
	}
	return nodes;
}
 
Example 19
/** Constructs an Image Header Box from a Node. */
public HeaderBox(Node node) throws IIOInvalidTreeException {
    super(node);
    NodeList children = node.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        String name = child.getNodeName();

        if ("Height".equals(name)) {
            height = Box.getIntElementValue(child);
        }

        if ("Width".equals(name)) {
            width = Box.getIntElementValue(child);
        }

        if ("NumComponents".equals(name)) {
            numComp = Box.getShortElementValue(child);
        }

        if ("BitDepth".equals(name)) {
            bitDepth = Box.getByteElementValue(child);
        }

        if ("CompressionType".equals(name)) {
            compressionType = Box.getByteElementValue(child);
        }

        if ("UnknownColorspace".equals(name)) {
            unknownColor = Box.getByteElementValue(child);
        }

        if ("IntellectualProperty".equals(name)) {
            intelProp = Box.getByteElementValue(child);
        }
    }
}
 
Example 20
@Override
public void deserialize(Model aModel, Document aDocument) {

    NodeList theElements = aDocument.getElementsByTagName(SUBJECTAREA);
    for (int i = 0; i < theElements.getLength(); i++) {
        Element theElement = (Element) theElements.item(i);

        SubjectArea theSubjectArea = new SubjectArea();
        deserializeProperties(theElement, theSubjectArea);

        theSubjectArea.setColor(new Color(Integer.parseInt(theElement.getAttribute(COLOR))));
        if (theElement.hasAttribute(VISIBLE)) {
            theSubjectArea.setVisible(TRUE.equals(theElement.getAttribute(VISIBLE)));
        }

        if (theElement.hasAttribute(EXPANDED)) {
            theSubjectArea.setExpanded(TRUE.equals(theElement.getAttribute(EXPANDED)));
        }

        NodeList theTables = theElement.getElementsByTagName(ITEM);
        for (int j = 0; j < theTables.getLength(); j++) {

            Element theItemElement = (Element) theTables.item(j);
            String theTableId = theItemElement.getAttribute(TABLEREFID);
            String theViewId = theItemElement.getAttribute(VIEWREFID);
            String theCommentId = theItemElement.getAttribute(COMMENTREFID);

            if (!StringUtils.isEmpty(theTableId)) {
                Table theTable = aModel.getTables().findBySystemId(theTableId);
                if (theTable == null) {
                    throw new IllegalArgumentException("Cannot find table with id " + theTableId);
                }

                theSubjectArea.getTables().add(theTable);
            }

            if (!StringUtils.isEmpty(theViewId)) {
                View theView = aModel.getViews().findBySystemId(theViewId);
                if (theView == null) {
                    throw new IllegalArgumentException("Cannot find view with id " + theViewId);
                }

                theSubjectArea.getViews().add(theView);
            }

            if (!StringUtils.isEmpty(theCommentId)) {
                Comment theComment = aModel.getComments().findBySystemId(theCommentId);
                if (theComment == null) {
                    throw new IllegalArgumentException("Cannot find comment with id " + theCommentId);
                }

                theSubjectArea.getComments().add(theComment);
            }
        }

        aModel.getSubjectAreas().add(theSubjectArea);
    }
}