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

The following examples show how to use org.w3c.dom.Node#getChildNodes() . 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: NYTCorpusDocumentParser.java    From ambiverse-nlu with Apache License 2.0 7 votes vote down vote up
private void handleHeadlineNode(Node node, NYTCorpusDocument ldcDocument) {
	NodeList children = node.getChildNodes();
	for (int i = 0; i < children.getLength(); i++) {
		Node child = children.item(i);
		String name = child.getNodeName();
		String text = getAllText(child).trim();
		if (name.equals(HL1_TAG)) {
			ldcDocument.setHeadline(text);
		} else if (name.equals(HL2_TAG)) {
			String classAttribute = getAttributeValue(child,
					CLASS_ATTRIBUTE);
			if (classAttribute != null
					&& classAttribute.equals(ONLINE_HEADLINE_ATTRIBUTE)) {
				ldcDocument.setOnlineHeadline(text);
			}
		}
	}
}
 
Example 2
Source File: MatrixParser.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
private static Atom parseAtom(Node node) {
    Node nameNode = node.getAttributes().getNamedItem("name");
    Map<String, String> props = new HashMap<String, String>();
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node item = childNodes.item(i);
        if ("properties".equals(item.getNodeName())) {
            props = parseProperties(item);
        }

    }

    Atom atom = new Atom();
    if (nameNode != null) {
        atom.setName(nameNode.getNodeValue());
    }
    atom.setProperties(props);
    return atom;
}
 
Example 3
Source File: RulesChecker.java    From container with Apache License 2.0 6 votes vote down vote up
private static Map<String, String> getPropertiesFromDoc(final Document doc) {

        final Map<String, String> propertiesMap = new HashMap<>();

        final NodeList nodeList = doc.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            final Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                final NodeList nodeList2 = node.getChildNodes();
                for (int i2 = 0; i2 < nodeList2.getLength(); i2++) {
                    final Node node2 = nodeList2.item(i2);
                    if (node2.getNodeType() == Node.ELEMENT_NODE) {
                        final String propName = node2.getNodeName();
                        final String propValue = node2.getTextContent();
                        LOG.debug("Property: " + propName + " has Value: " + propValue);
                        if (propName != null && propValue != null) {
                            propertiesMap.put(node2.getNodeName(), node2.getTextContent());
                        }
                    }
                }
            }
        }
        return propertiesMap;
    }
 
Example 4
Source File: XmlUtils.java    From OpenEstate-IO with Apache License 2.0 6 votes vote down vote up
/**
 * Replace all text values of a {@link Node} with CDATA values.
 *
 * @param doc  the document to update
 * @param node the node to update
 */
public static void replaceTextWithCData(Document doc, Node node) {
    if (node instanceof Text) {
        Text text = (Text) node;
        CDATASection cdata = doc.createCDATASection(text.getTextContent());
        Element parent = (Element) text.getParentNode();
        parent.replaceChild(cdata, text);
    } else if (node instanceof Element) {
        //LOGGER.debug( "ELEMENT " + element.getTagName() );
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            //LOGGER.debug( "> " + children.item( i ).getClass().getName() );
            XmlUtils.replaceTextWithCData(doc, children.item(i));
        }
    }
}
 
Example 5
Source File: JPEGMetadata.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void mergeStandardTextNode(Node node)
    throws IIOInvalidTreeException {
    // Convert to comments.  For the moment ignore the encoding issue.
    // Ignore keywords, language, and encoding (for the moment).
    // If compression tag is present, use only entries with "none".
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        NamedNodeMap attrs = child.getAttributes();
        Node comp = attrs.getNamedItem("compression");
        boolean copyIt = true;
        if (comp != null) {
            String compString = comp.getNodeValue();
            if (!compString.equals("none")) {
                copyIt = false;
            }
        }
        if (copyIt) {
            String value = attrs.getNamedItem("value").getNodeValue();
            COMMarkerSegment com = new COMMarkerSegment(value);
            insertCOMMarkerSegment(com);
        }
    }
}
 
Example 6
Source File: PDFolders.java    From openprodoc with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Import a Folder(s) described by an XML with content referenced
 * @param OPDObject XMLNode to process
 * @param ParentFolderId OPD destination folder
 * @param MaintainId When true, the Original Id is maintained, else a new one is assigned
 * @return The PDFolder of the imported Folder
 * @throws PDException In any error
 */
public PDFolders ImportXMLNode(Node OPDObject, String ParentFolderId, boolean MaintainId) throws PDException
{
NodeList childNodes = OPDObject.getChildNodes();
PDFolders NewFold=null;
PDObjDefs DefDoc=new PDObjDefs(getDrv());
for (int i = 0; i < childNodes.getLength(); i++)
    {
    Node item = childNodes.item(i);
    if (item.getNodeName().equalsIgnoreCase(XML_ListAttr)) 
        {
        Record r=Record.FillFromXML(item, getRecord());
        String FoldTypReaded=(String)r.getAttr(PDFolders.fFOLDTYPE).getValue();
        if (DefDoc.Load(FoldTypReaded)==null)
           throw new PDException("Unknown_FoldType"+":"+FoldTypReaded);          
        NewFold=new PDFolders(getDrv(), FoldTypReaded); // to be improved to analize the type BEFORE
        r=Record.FillFromXML(item, NewFold.getRecSum());
        NewFold.assignValues(r);
        if (!MaintainId && ExistId(NewFold.getPDId()))
            NewFold.setPDId(null);
        NewFold.setParentId(ParentFolderId);
        }
    }
NewFold.insert();
return NewFold;
}
 
Example 7
Source File: DOMUtils.java    From hkxpack with MIT License 6 votes vote down vote up
/**
 * Retrieves a {@link Node} attribute froma {@link NodeList}.
 * @param tagName the tagName of the node to retrieve
 * @param attrName the attribute name to retrieve
 * @param nodes the {@link NodeList} to retrieve from.
 * @return the relevant attribute, or "".
 */
public static String getNodeAttr(final String tagName, final String attrName, final NodeList nodes ) {
    for(int x = 0; x < nodes.getLength(); x++) {
        Node node = nodes.item(x);
        if(node.getNodeName().equalsIgnoreCase(tagName)) {
            NodeList childNodes = node.getChildNodes();
            for(int y = 0; y < childNodes.getLength(); y++) {
                Node data = childNodes.item(y);
                if(data.getNodeType() == Node.ATTRIBUTE_NODE && data.getNodeName().equalsIgnoreCase(attrName)) {
                	return data.getNodeValue();
                }
            }
        }
    }
    return "";
}
 
Example 8
Source File: UtilLoggingXmlLogImporter.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
protected String getExceptionStackTrace(Node eventNode) {
  StringBuilder sb = new StringBuilder();
  NodeList childNodes = eventNode.getChildNodes();
  for (int i = 0; i < childNodes.getLength(); i++) {
    Node childNode = childNodes.item(i);
    String tagName = childNode.getNodeName();
    if (tagName.equalsIgnoreCase("message")) {
      sb.append(getCData(childNodes.item(i)));
    } else if (tagName.equalsIgnoreCase("frame")) {
      getStackTraceFrame(childNodes.item(i), sb);
    }
  }

  return sb.toString();

}
 
Example 9
Source File: NYTCorpusDocumentParser.java    From CLIFF with Apache License 2.0 5 votes vote down vote up
private void handleDocdataNode(Node node, NYTCorpusDocument ldcDocument) {
	NodeList children = node.getChildNodes();
	for (int i = 0; i < children.getLength(); i++) {
		Node child = children.item(i);
		String name = child.getNodeName();
		if (name.equals(DOC_ID_TAG)) {
			handleDocumentIdNode(ldcDocument, child);
		} else if (name.equals(SERIES_TAG)) {
			ldcDocument
					.setKicker(getAttributeValue(child, SERIES_NAME_TAG));
		} else if (name.equals(IDENTIFIED_CONTENT_TAG)) {
			handleIdentifiedContent(child, ldcDocument);
		}
	}
}
 
Example 10
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 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 11
Source File: MyBatisGeneratorConfigurationParser.java    From mapper-generator-javafx with Apache License 2.0 5 votes vote down vote up
private void parseJavaClientGenerator(Context context, Node node) {
    JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();

    context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

    Properties attributes = parseAttributes(node);
    String type = attributes.getProperty("type");
    String targetPackage = attributes.getProperty("targetPackage");
    String targetProject = attributes.getProperty("targetProject");
    String implementationPackage = attributes
            .getProperty("implementationPackage");

    javaClientGeneratorConfiguration.setConfigurationType(type);
    javaClientGeneratorConfiguration.setTargetPackage(targetPackage);
    javaClientGeneratorConfiguration.setTargetProject(targetProject);
    javaClientGeneratorConfiguration
            .setImplementationPackage(implementationPackage);

    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())) {
            parseProperty(javaClientGeneratorConfiguration, childNode);
        }
    }
}
 
Example 12
Source File: Util.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static List<Element> getChildElementsByTag(Node parent, String tag) {
    List<Element> children = new ArrayList<Element>();
    NodeList nl = parent.getChildNodes();
    for (int i=0; i<nl.getLength(); i++) {
        if (nl.item(i) instanceof Element) {
            Element e = (Element) nl.item(i);
            if (e.getTagName().equals(tag))
                children.add(e);
        }
    }
    return children;
}
 
Example 13
Source File: MetsUtils.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private static void findChildPSPs(DigitalObject dObj, MetsContext ctx, List<String> psps, String parentType) throws MetsExportException {
    List<Element> relsExt = FoxmlUtils.findDatastream(dObj, "RELS-EXT").getDatastreamVersion().get(0).getXmlContent().getAny();
    Node node = MetsUtils.xPathEvaluateNode(relsExt, "*[local-name()='RDF']/*[local-name()='Description']");

    NodeList hasPageNodes = node.getChildNodes();
    for (int a = 0; a < hasPageNodes.getLength(); a++) {
        if (MetsUtils.hasReferenceXML(hasPageNodes.item(a).getNodeName())) {
            Node rdfResourceNode = hasPageNodes.item(a).getAttributes().getNamedItem("rdf:resource");
            String fileName = rdfResourceNode.getNodeValue();

            DigitalObject object = null;
            if (ctx.getFedoraClient() != null) {
                object = MetsUtils.readRelatedFoXML(fileName, ctx.getFedoraClient());
            } else {
                object = MetsUtils.readRelatedFoXML(ctx.getPath(), fileName);
            }
            relsExt = FoxmlUtils.findDatastream(object, "RELS-EXT").getDatastreamVersion().get(0).getXmlContent().getAny();
            String model = MetsUtils.getModel(relsExt);
            String elementType = getElementType(model);

            if (Const.PSPElements.contains(elementType)) {
                if (((Const.MONOGRAPH_UNIT.equals(parentType) || (Const.ISSUE.equals(parentType)))) && (Const.SUPPLEMENT.equals(elementType))) {
                    // do not add
                } else {
                    psps.add(object.getPID());
                }
            } else {
                findChildPSPs(object, ctx, psps, elementType);
            }
        }
    }
}
 
Example 14
Source File: NodeUtils.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
static Node duplicateNode(Document document, Node node) {
    Node newNode;
    if (node.getNamespaceURI() != null) {
        newNode = document.createElementNS(node.getNamespaceURI(), node.getLocalName());
    } else {
        newNode = document.createElement(node.getNodeName());
    }

    // copy the attributes
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0 ; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);

        Attr newAttr;
        if (attr.getNamespaceURI() != null) {
            newAttr = document.createAttributeNS(attr.getNamespaceURI(), attr.getLocalName());
            newNode.getAttributes().setNamedItemNS(newAttr);
        } else {
            newAttr = document.createAttribute(attr.getName());
            newNode.getAttributes().setNamedItem(newAttr);
        }

        newAttr.setValue(attr.getValue());
    }

    // then duplicate the sub-nodes.
    NodeList children = node.getChildNodes();
    for (int i = 0 ; i < children.getLength() ; i++) {
        Node child = children.item(i);
        if (child.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        Node duplicatedChild = duplicateNode(document, child);
        newNode.appendChild(duplicatedChild);
    }

    return newNode;
}
 
Example 15
Source File: RuleSetFactory.java    From dacapobench with Apache License 2.0 5 votes vote down vote up
/**
 * Process a rule descrtiprion node
 * @param rule the rule being constructed
 * @param descriptionNode must be a description element node
 */
private void parseDescriptionNode(Rule rule, Node descriptionNode) {
    NodeList nodeList = descriptionNode.getChildNodes();
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.CDATA_SECTION_NODE) {
            buffer.append(node.getNodeValue());
        } else if (node.getNodeType() == Node.TEXT_NODE) {
            buffer.append(node.getNodeValue());
        }
    }
    rule.setDescription(buffer.toString());
}
 
Example 16
Source File: XMLMatchableReader.java    From winter with Apache License 2.0 5 votes vote down vote up
/**
 * returns a list of values from a child node of the first parameter. The
 * list values are expected to be atomic, i.e. no complex node structures
 * 
 * @param node
 *            the node containing the data
 * @param childName
 *            the name of the child node
 * @return a list of values from the specified child node
 */
protected List<String> getListFromChildElement(Node node, String childName) {

	// get all child nodes
	NodeList children = node.getChildNodes();

	// iterate over the child nodes until the node with childName is found
	for (int j = 0; j < children.getLength(); j++) {
		Node child = children.item(j);

		// check the node type and name
		if (child.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE
				&& child.getNodeName().equals(childName)) {

			// prepare a list to hold all values
			List<String> values = new ArrayList<>(child.getChildNodes()
					.getLength());

			// iterate the value nodes
			for (int i = 0; i < child.getChildNodes().getLength(); i++) {
				Node valueNode = child.getChildNodes().item(i);
				String value = valueNode.getTextContent().trim();

				// add the value
				values.add(value);
			}

			return values;
		}
	}

	return null;
}
 
Example 17
Source File: XmlBeansMarshaller.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void marshalDomNode(Object graph, Node node) throws XmlMappingException {
	Document document = (node.getNodeType() == Node.DOCUMENT_NODE ? (Document) node : node.getOwnerDocument());
	Node xmlBeansNode = ((XmlObject) graph).newDomNode(getXmlOptions());
	NodeList xmlBeansChildNodes = xmlBeansNode.getChildNodes();
	for (int i = 0; i < xmlBeansChildNodes.getLength(); i++) {
		Node xmlBeansChildNode = xmlBeansChildNodes.item(i);
		Node importedNode = document.importNode(xmlBeansChildNode, true);
		node.appendChild(importedNode);
	}
}
 
Example 18
Source File: SOSMarkerSegment.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void updateFromNativeNode(Node node, boolean fromScratch)
    throws IIOInvalidTreeException {
    NamedNodeMap attrs = node.getAttributes();
    int numComponents = getAttributeValue(node, attrs, "numScanComponents",
                                          1, 4, true);
    int value = getAttributeValue(node, attrs, "startSpectralSelection",
                                  0, 63, false);
    startSpectralSelection = (value != -1) ? value : startSpectralSelection;
    value = getAttributeValue(node, attrs, "endSpectralSelection",
                              0, 63, false);
    endSpectralSelection = (value != -1) ? value : endSpectralSelection;
    value = getAttributeValue(node, attrs, "approxHigh", 0, 15, false);
    approxHigh = (value != -1) ? value : approxHigh;
    value = getAttributeValue(node, attrs, "approxLow", 0, 15, false);
    approxLow = (value != -1) ? value : approxLow;

    // Now the children
    NodeList children = node.getChildNodes();
    if (children.getLength() != numComponents) {
        throw new IIOInvalidTreeException
            ("numScanComponents must match the number of children", node);
    }
    componentSpecs = new ScanComponentSpec[numComponents];
    for (int i = 0; i < numComponents; i++) {
        componentSpecs[i] = new ScanComponentSpec(children.item(i));
    }
}
 
Example 19
Source File: ConfigurationParser.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the input stream from the CTF configuration file
 * and fills <code>registeredClasses</code> and <code>registeredListeners</code>
 * with classes found.
 * @param inputStream - the input stream
 * @param classLoader - the class loader for the current thread
 * @throws ClassNotFoundException - if class is not found
 */
public void parse( InputStream inputStream, String systemID ) throws ClassNotFoundException, IOException,
                                                              SAXException, ParserConfigurationException,
                                                              AgentException {

    inititalizeParser(inputStream, systemID);
    initializeComponentMetaData();

    NodeList list = mDocument.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        Node childNode = list.item(i);
        if (childNode.getNodeType() == Node.ELEMENT_NODE
            && childNode.getNodeName().equals(COMPONENT)) {
            componentName = childNode.getAttributes().getNamedItem("name").getNodeValue();

            NodeList componentSubElementsList = childNode.getChildNodes();
            for (int k = 0; k < componentSubElementsList.getLength(); k++) {
                Node componentSubElement = componentSubElementsList.item(k);

                if (componentSubElement.getNodeName().equals(ACTION_CLASS)) {
                    String nameAttribute = componentSubElement.getAttributes()
                                                              .getNamedItem("name")
                                                              .getNodeValue();
                    actionClassNames.add(nameAttribute);
                } else if (componentSubElement.getNodeName().equals(INITIALIZATION_HANDLER)) {
                    initializationHandler = componentSubElement.getAttributes()
                                                               .getNamedItem("name")
                                                               .getNodeValue();
                } else if (componentSubElement.getNodeName().equals(FINALIZATION_HANDLER)) {
                    finalizationHandler = componentSubElement.getAttributes()
                                                             .getNamedItem("name")
                                                             .getNodeValue();
                } else if (componentSubElement.getNodeName().equals(CLEANUP_HANDLER)) {
                    cleanupHandler = componentSubElement.getAttributes()
                                                        .getNamedItem("name")
                                                        .getNodeValue();
                } else if (componentSubElement.getNodeName().equals(ENVIRONMENT)) {
                    parseEnvironment(componentSubElement);
                }
            }
        }
    }
}
 
Example 20
Source File: XAdESReferenceValidation.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns a complete description string for the given transformation node
 * @param transformation {@link Node} containing a signle reference transformation information
 * @return transformation description name
 */
private String buildTransformationName(Node transformation) {
	String algorithmUri = DomUtils.getValue(transformation, "@Algorithm");
	String algorithm = algorithmUri;
	if (presentableTransformationNames.containsKey(algorithmUri)) {
		algorithm = presentableTransformationNames.get(algorithmUri);
	}
	StringBuilder stringBuilder = new StringBuilder(algorithm);
	if (transformation.hasChildNodes()) {
		NodeList childNodes = transformation.getChildNodes();
		stringBuilder.append(" (");
		boolean hasValues = false;
		
		for (int ii = 0; ii < childNodes.getLength(); ii++) {
			Node parameterNode = childNodes.item(ii);
			if (Node.ELEMENT_NODE != parameterNode.getNodeType()) {
				continue;
			}

			// attach attribute values
			NamedNodeMap attributes = parameterNode.getAttributes();
			for (int jj = 0; jj < attributes.getLength(); jj++) {
				Node attribute = attributes.item(jj);
				String attrName = attribute.getLocalName();
				String attrValue = attribute.getNodeValue();
				if (algorithmUri.equals(attrValue)) {
					continue; // skip the case when the algorithm uri is defined in a child node
				}
				if (hasValues) {
					stringBuilder.append("; ");
				}
				stringBuilder.append(attrName).append(": ");
				stringBuilder.append(attrValue);
				hasValues = true;
			}
			
			// attach node value
			Node parameterValueNode = parameterNode.getFirstChild();
			if (parameterValueNode != null && Node.TEXT_NODE == parameterValueNode.getNodeType() &&
					Utils.isStringNotBlank(parameterValueNode.getTextContent())) {
				if (hasValues) {
					stringBuilder.append("; ");
				}
				stringBuilder.append(parameterNode.getLocalName()).append(": ");
				stringBuilder.append(parameterValueNode.getTextContent());
				hasValues = true;
			}
		}
		stringBuilder.append(")");
	}
	return stringBuilder.toString();
}