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

The following examples show how to use org.w3c.dom.Node#getNodeType() . 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 openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/** Finds and returns the first child node with the given qualified name. */
public static Element getFirstChildElementNS(Node parent,
        String[][] elemNames) {

    // search for node
    Node child = parent.getFirstChild();
    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.getNextSibling();
    }

    // not found
    return null;

}
 
Example 2
Source File: ActionMappingScanner.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Scan through Element named reload.
 */
void visitElement_reload(Element element) {
    // <reload>
    // element.getValue();
    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        if (attr.getName().equals("rule")) {
            mapping.reloadRule = ActionMapping.ReloadRule.valueOf(attr.getValue());
        }
    }
    NodeList nodes = element.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        switch (node.getNodeType()) {
            case Node.ELEMENT_NODE:
                Element nodeElement = (Element) node;
                if (nodeElement.getTagName().equals("args")) {
                    mapping.reloadArgs = visitElement_args(nodeElement);
                }
                break;
        }
    }
}
 
Example 3
Source File: SignatureUtils.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Collection<Element> getXAdESChildElements(
        Element xmlObjectElem)
{
    Collection<Element> xadesElems = new ArrayList<Element>(1);

    Node child = xmlObjectElem.getFirstChild();
    while (child != null)
    {
        if (child.getNodeType() == Node.ELEMENT_NODE && QualifyingProperty.XADES_XMLNS.equals(child.getNamespaceURI()))
        {
            xadesElems.add((Element) child);
        }
        child = child.getNextSibling();
    }

    return xadesElems;
}
 
Example 4
Source File: KeyInfo.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method itemUnknownElement
 *
 * @param i index
 * @return the element number of the unknown elements
 */
public Element itemUnknownElement(int i) {
    NodeList nl = this.constructionElement.getChildNodes();
    int res = 0;

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

        /**
         * $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++;

            if (res == i) {
                return (Element) current;
            }
        }
    }

    return null;
}
 
Example 5
Source File: StreamHeader.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
    try {
        // TODO what about in-scope namespaces
        // Not very efficient consider implementing a stream buffer
        // processor that produces a DOM node from the buffer.
        TransformerFactory tf = XmlUtil.newTransformerFactory();
        Transformer t = tf.newTransformer();
        XMLStreamBufferSource source = new XMLStreamBufferSource(_mark);
        DOMResult result = new DOMResult();
        t.transform(source, result);
        Node d = result.getNode();
        if(d.getNodeType() == Node.DOCUMENT_NODE)
            d = d.getFirstChild();
        SOAPHeader header = saaj.getSOAPHeader();
        if(header == null)
            header = saaj.getSOAPPart().getEnvelope().addHeader();
        Node node = header.getOwnerDocument().importNode(d, true);
        header.appendChild(node);
    } catch (Exception e) {
        throw new SOAPException(e);
    }
}
 
Example 6
Source File: SOAPActionProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
protected Element readBodyElement(Document d) {

        Element envelopeElement = d.getDocumentElement();
        
        if (envelopeElement == null || !getUnprefixedNodeName(envelopeElement).equals("Envelope")) {
            throw new RuntimeException("Response root element was not 'Envelope'");
        }

        NodeList envelopeElementChildren = envelopeElement.getChildNodes();
        for (int i = 0; i < envelopeElementChildren.getLength(); i++) {
            Node envelopeChild = envelopeElementChildren.item(i);

            if (envelopeChild.getNodeType() != Node.ELEMENT_NODE)
                continue;

            if (getUnprefixedNodeName(envelopeChild).equals("Body")) {
                return (Element) envelopeChild;
            }
        }

        throw new RuntimeException("Response envelope did not contain 'Body' child element");
    }
 
Example 7
Source File: Body1_2Impl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private boolean hasAnyChildElement() {
    Node currentNode = getFirstChild();
    while (currentNode != null) {
        if (currentNode.getNodeType() == Node.ELEMENT_NODE)
            return true;
        currentNode = currentNode.getNextSibling();
    }
    return false;
}
 
Example 8
Source File: DTMNodeProxy.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param tagname
 *
 *
 * @see org.w3c.dom.Document
 */
@Override
public final NodeList getElementsByTagName(String tagname)
{
     Vector listVector = new Vector();
     Node retNode = dtm.getNode(node);
     if (retNode != null)
     {
       boolean isTagNameWildCard = "*".equals(tagname);
       if (DTM.ELEMENT_NODE == retNode.getNodeType())
       {
         NodeList nodeList = retNode.getChildNodes();
         for (int i = 0; i < nodeList.getLength(); i++)
         {
           traverseChildren(listVector, nodeList.item(i), tagname,
                            isTagNameWildCard);
         }
       } else if (DTM.DOCUMENT_NODE == retNode.getNodeType()) {
         traverseChildren(listVector, dtm.getNode(node), tagname,
                          isTagNameWildCard);
       }
     }
     int size = listVector.size();
     NodeSet nodeSet = new NodeSet(size);
     for (int i = 0; i < size; i++)
     {
       nodeSet.addNode((Node) listVector.elementAt(i));
     }
     return (NodeList) nodeSet;
}
 
Example 9
Source File: DOMStreamReader.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method is not particularly fast, but shouldn't be called very
 * often. If we start to use it more, we should keep track of the
 * NS declarations using a NamespaceContext implementation instead.
 */
public String getNamespaceURI(String prefix) {
    if (prefix == null) {
        throw new IllegalArgumentException("DOMStreamReader: getNamespaceURI(String) call with a null prefix");
    }
    else if (prefix.equals("xml")) {
        return "http://www.w3.org/XML/1998/namespace";
    }
    else if (prefix.equals("xmlns")) {
        return "http://www.w3.org/2000/xmlns/";
    }

    // check scopes
    String nsUri = scopes[depth].getNamespaceURI(prefix);
    if(nsUri!=null)    return nsUri;

    // then ancestors above start node
    Node node = findRootElement();
    String nsDeclName = prefix.length()==0 ? "xmlns" : "xmlns:"+prefix;
    while (node.getNodeType() != DOCUMENT_NODE) {
        // Is ns declaration on this element?
        NamedNodeMap namedNodeMap = node.getAttributes();
        Attr attr = (Attr) namedNodeMap.getNamedItem(nsDeclName);
        if (attr != null)
            return attr.getValue();
        node = node.getParentNode();
    }
    return null;
}
 
Example 10
Source File: DOMResultAugmentor.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
public void setDOMResult(DOMResult result) {
    fIgnoreChars = false;
    if (result != null) {
        final Node target = result.getNode();
        fDocument = (target.getNodeType() == Node.DOCUMENT_NODE) ? (Document) target : target.getOwnerDocument();
        fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null;
        fStorePSVI = (fDocument instanceof PSVIDocumentImpl);
        return;
    }
    fDocument = null;
    fDocumentImpl = null;
    fStorePSVI = false;
}
 
Example 11
Source File: UDA10ServiceDescriptorBinderImpl.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
protected void hydrateRoot(MutableService descriptor, Element rootElement)
        throws DescriptorBindingException {

    // We don't check the XMLNS, nobody bothers anyway...

    if (!ELEMENT.scpd.equals(rootElement)) {
        throw new DescriptorBindingException("Root element name is not <scpd>: " + rootElement.getNodeName());
    }

    NodeList rootChildren = rootElement.getChildNodes();

    for (int i = 0; i < rootChildren.getLength(); i++) {
        Node rootChild = rootChildren.item(i);

        if (rootChild.getNodeType() != Node.ELEMENT_NODE)
            continue;

        if (ELEMENT.specVersion.equals(rootChild)) {
            // We don't care about UDA major/minor specVersion anymore - whoever had the brilliant idea that
            // the spec versions can be declared on devices _AND_ on their services should have their fingers
            // broken so they never touch a keyboard again.
            // hydrateSpecVersion(descriptor, rootChild);
        } else if (ELEMENT.actionList.equals(rootChild)) {
            hydrateActionList(descriptor, rootChild);
        } else if (ELEMENT.serviceStateTable.equals(rootChild)) {
            hydrateServiceStateTableList(descriptor, rootChild);
        } else {
            log.finer("Ignoring unknown element: " + rootChild.getNodeName());
        }
    }

}
 
Example 12
Source File: DOMUtilsNS.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
private static void getElementsWithAttribute(Element element, String namespaceURI, String localName, String value, Collection elements) {
   if (element.hasAttributeNS(namespaceURI, localName)) {
     String attr = element.getAttributeNS(namespaceURI, localName);
     if (attr.equals(value)) elements.add(element);
   }

   NodeList childs = element.getChildNodes();

   for (int i = 0; i < childs.getLength(); i++) {
     Node node = childs.item(i);
     if (Node.ELEMENT_NODE == node.getNodeType())
getElementsWithAttribute((Element) node, namespaceURI, localName, value, elements);
   }
 }
 
Example 13
Source File: DOMUtils.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first child of the specified type.
 *
 * @param parent
 * @param 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 14
Source File: XMLUtils.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param sibling
 * @param uri
 * @param nodeName
 * @param number
 * @return nodes with the constrain
 */
public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) {
    Node n = selectNode(sibling,uri,nodeName,number);
    if (n == null) {
        return null;
    }
    n = n.getFirstChild();
    while (n != null && n.getNodeType() != Node.TEXT_NODE) {
        n = n.getNextSibling();
    }
    return (Text)n;
}
 
Example 15
Source File: XmlModuleConfigRepository.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private static Map<Object, Object> readProperties(Node moduleNode) {
    Map<Object, Object> properties = new HashMap<>();
    NodeList propertyNodes = moduleNode.getChildNodes();
    for (int i = 0; i < propertyNodes.getLength(); i++) {
        Node propertyNode = propertyNodes.item(i);
        if (propertyNode.getNodeType() == Node.ELEMENT_NODE) {
            String propertyName = propertyNode.getLocalName();
            Node child = propertyNode.getFirstChild();
            String propertyValue = child != null ? child.getTextContent() : "";
            properties.put(propertyName, propertyValue);
        }
    }
    return properties;
}
 
Example 16
Source File: RangeImpl.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public String toString(){
    if( fDetach) {
            throw new DOMException(
            DOMException.INVALID_STATE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null));
    }

    Node node = fStartContainer;
    Node stopNode = fEndContainer;
    StringBuffer sb = new StringBuffer();
    if (fStartContainer.getNodeType() == Node.TEXT_NODE
     || fStartContainer.getNodeType() == Node.CDATA_SECTION_NODE
    ) {
        if (fStartContainer == fEndContainer) {
            sb.append(fStartContainer.getNodeValue().substring(fStartOffset, fEndOffset));
            return sb.toString();
        }
        sb.append(fStartContainer.getNodeValue().substring(fStartOffset));
        node=nextNode (node,true); //fEndContainer!=fStartContainer

    }
    else {  //fStartContainer is not a TextNode
        node=node.getFirstChild();
        if (fStartOffset>0) { //find a first node within a range, specified by fStartOffset
           int counter=0;
           while (counter<fStartOffset && node!=null) {
               node=node.getNextSibling();
               counter++;
           }
        }
        if (node == null) {
               node = nextNode(fStartContainer,false);
        }
    }
    if ( fEndContainer.getNodeType()!= Node.TEXT_NODE &&
         fEndContainer.getNodeType()!= Node.CDATA_SECTION_NODE ){
         int i=fEndOffset;
         stopNode = fEndContainer.getFirstChild();
         while( i>0 && stopNode!=null ){
             --i;
             stopNode = stopNode.getNextSibling();
         }
         if ( stopNode == null )
             stopNode = nextNode( fEndContainer, false );
     }
     while (node != stopNode) {  //look into all kids of the Range
         if (node == null) break;
         if (node.getNodeType() == Node.TEXT_NODE
         ||  node.getNodeType() == Node.CDATA_SECTION_NODE) {
             sb.append(node.getNodeValue());
         }

         node = nextNode(node, true);
     }

    if (fEndContainer.getNodeType() == Node.TEXT_NODE
     || fEndContainer.getNodeType() == Node.CDATA_SECTION_NODE) {
        sb.append(fEndContainer.getNodeValue().substring(0,fEndOffset));
    }
    return sb.toString();
}
 
Example 17
Source File: XMLUtils.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("fallthrough")
private static void getSetRec(final Node rootNode, final Set<Node> result,
                            final Node exclude, final boolean com) {
    if (rootNode == exclude) {
        return;
    }
    switch (rootNode.getNodeType()) {
    case Node.ELEMENT_NODE:
        result.add(rootNode);
        Element el = (Element)rootNode;
        if (el.hasAttributes()) {
            NamedNodeMap nl = el.getAttributes();
            for (int i = 0;i < nl.getLength(); i++) {
                result.add(nl.item(i));
            }
        }
        //no return keep working
    case Node.DOCUMENT_NODE:
        for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) {
            if (r.getNodeType() == Node.TEXT_NODE) {
                result.add(r);
                while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) {
                    r = r.getNextSibling();
                }
                if (r == null) {
                    return;
                }
            }
            getSetRec(r, result, exclude, com);
        }
        return;
    case Node.COMMENT_NODE:
        if (com) {
            result.add(rootNode);
        }
        return;
    case Node.DOCUMENT_TYPE_NODE:
        return;
    default:
        result.add(rootNode);
    }
}
 
Example 18
Source File: TomcatConfigReadin.java    From bestconf with Apache License 2.0 4 votes vote down vote up
private static void writetoConfigfile(HashMap hm) {
	String iniConf = "data/server-initial.xml", updatedConf="data/server.xml";
	
	try {
		//we first read in the base line
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dbBuilder;
		dbBuilder = dbFactory.newDocumentBuilder();
		Document doc = dbBuilder.parse(new File(iniConf));
		
		//now we find the place to change
		NodeList connList = doc.getElementsByTagName("Connector");
		boolean done = false;
		for (int i = 0; i < connList.getLength() && !done; i++) {
			Node connNode = connList.item(i);
			if (connNode.getNodeType() == Node.ELEMENT_NODE) {
				 NamedNodeMap map = connNode.getAttributes();
				 for(int j=0;j<map.getLength() && !done;j++){
					 if(map.item(j).getNodeName().equals("port") &&
							 map.item(j).getNodeValue().equals("8080")){
						 /** now we update the config file as needed*/
						 Element ele = (Element)connNode;
						 for(Object obj : hm.entrySet()){
							 Map.Entry ent = (Map.Entry)obj;
							 ele.setAttribute(ent.getKey().toString(), ent.getValue().toString());
						 }
						 done=true;
					 }
				 }
			}
		}
		
		//updated! we write the config out to file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(updatedConf));
		transformer.transform(source, result);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 19
Source File: EntryParserImpl.java    From google-sites-liberation with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the given element, populating the given entry with its data.
 */
private void parseElement(Element element, BaseContentEntry<?> entry) {
  NodeList nodeList = element.getChildNodes();
  for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
    if (node.getNodeType() == Node.ELEMENT_NODE) {
      Element child = (Element) node;
      if (!hasClass(child, "hentry") && !child.getTagName().equals("q")
          && !child.getTagName().equals("blockquote")) {
        boolean parseDeeper = true;
        if (hasClass(child, "entry-title")) {
          entry.setTitle(titleParser.parseTitle(child));
          parseDeeper = false;
        } 
        if (hasClass(child, "entry-content")) {
          entry.setContent(contentParser.parseContent(child));
          parseDeeper = false;
        } 
        if (hasClass(child, "updated")) {
          entry.setUpdated(updatedParser.parseUpdated(child));
          parseDeeper = false;
        } 
        if (hasClass(child, "vcard")) {
          entry.getAuthors().add(authorParser.parseAuthor(child));
          parseDeeper = false;
        } 
        if (hasClass(child, "entry-summary")) {
          entry.setSummary(summaryParser.parseSummary(child));
          parseDeeper = false;
        } 
        if (hasClass(child, "gs:data")) {
          if (getType(entry) == LIST_PAGE) {
            // TODO(gk5885): remove extra cast for
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302214
            ((ListPageEntry) (BaseContentEntry) entry).setData(dataParser.parseData(child));
          }
          parseDeeper = false;
        } 
        if (hasClass(child, "gs:field")) {
          if (getType(entry) == LIST_ITEM) {
            // TODO(gk5885): remove extra cast for
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302214
            ((ListItemEntry) (BaseContentEntry) entry).addField(fieldParser.parseField(child));
          }
          parseDeeper = false;
        }
        if (parseDeeper) {
          parseElement(child, entry);
        }
      }
    }
  }
}
 
Example 20
Source File: DOMBuilder.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Append a node to the current container.
 *
 * @param newNode New node to append
 */
protected void append(Node newNode) throws org.xml.sax.SAXException
{

  Node currentNode = m_currentNode;

  if (null != currentNode)
  {
    if (currentNode == m_root && m_nextSibling != null)
      currentNode.insertBefore(newNode, m_nextSibling);
    else
      currentNode.appendChild(newNode);

    // System.out.println(newNode.getNodeName());
  }
  else if (null != m_docFrag)
  {
    if (m_nextSibling != null)
      m_docFrag.insertBefore(newNode, m_nextSibling);
    else
      m_docFrag.appendChild(newNode);
  }
  else
  {
    boolean ok = true;
    short type = newNode.getNodeType();

    if (type == Node.TEXT_NODE)
    {
      String data = newNode.getNodeValue();

      if ((null != data) && (data.trim().length() > 0))
      {
        throw new org.xml.sax.SAXException(
          XMLMessages.createXMLMessage(
            XMLErrorResources.ER_CANT_OUTPUT_TEXT_BEFORE_DOC, null));  //"Warning: can't output text before document element!  Ignoring...");
      }

      ok = false;
    }
    else if (type == Node.ELEMENT_NODE)
    {
      if (m_doc.getDocumentElement() != null)
      {
        ok = false;

        throw new org.xml.sax.SAXException(
          XMLMessages.createXMLMessage(
            XMLErrorResources.ER_CANT_HAVE_MORE_THAN_ONE_ROOT, null));  //"Can't have more than one root on a DOM!");
      }
    }

    if (ok)
    {
      if (m_nextSibling != null)
        m_doc.insertBefore(newNode, m_nextSibling);
      else
        m_doc.appendChild(newNode);
    }
  }
}