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

The following examples show how to use org.w3c.dom.NodeList#getLength() . 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: XMLUtil.java    From ns4_frame with 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 2
Source File: XMLUtils.java    From mzmine3 with 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 3
Source File: XmlFileMergerJaxp.java    From mapper-generator-javafx with Apache License 2.0 6 votes vote down vote up
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 4
Source File: DPPParameterValueWrapper.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
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 5
Source File: TemplateRegistration.java    From azure-notificationhubs-android with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: DalConfigureFactory.java    From das with 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
Source File: XMLBox.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 6 votes vote down vote up
/** 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 8
Source File: TypeReader.java    From arcusplatform with 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 9
Source File: DubboBeanDefinitionParser.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
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 10
Source File: ExsltMath.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 11
Source File: CommonAbstractXMLSerializer.java    From MogwaiERDesignerNG with GNU General Public License v3.0 5 votes vote down vote up
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 12
Source File: HeaderBox.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 5 votes vote down vote up
/** 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 13
Source File: DBUtils.java    From micro-integrator with 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 14
Source File: BaseDefinitionReader.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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 15
Source File: SpringBootStarterMojo.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
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 16
Source File: LipidModificationChoiceParameter.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@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 17
Source File: BeanDefinitionParserDelegate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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 18
Source File: DHTMarkerSegment.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 19
Source File: BaseDefinitionReader.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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 20
Source File: XMLSubjectAreaSerializer.java    From MogwaiERDesignerNG with GNU General Public License v3.0 4 votes vote down vote up
@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);
    }
}