Java Code Examples for org.w3c.dom.NamedNodeMap#item()

The following examples show how to use org.w3c.dom.NamedNodeMap#item() . 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: Namespaces.java    From ttt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static void normalize(Element elt, Map<String,String> normalizedPrefixes, String[] na, int[] ca) {
    normalizeNode((Node) elt, normalizedPrefixes, na, ca);
    NamedNodeMap attrs = elt.getAttributes();
    List<Attr> xmlnsFixups = new java.util.ArrayList<Attr>();
    for (int i = 0, n = attrs.getLength(); i < n; ++i) {
        Node node = attrs.item(i);
        if (node instanceof Attr) {
            String nsUri = node.getNamespaceURI();
            if ((nsUri != null) && nsUri.equals(XML.xmlnsNamespace))
                xmlnsFixups.add((Attr) node);
            else
                normalizeNode(node, normalizedPrefixes, na, ca);
        }
    }
    for (Attr a : xmlnsFixups)
        normalizeDeclaration(a, elt, normalizedPrefixes);
}
 
Example 2
Source File: NacosDataXmlParser.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
private void parseNodeAttr(NamedNodeMap nodeMap, Map<String, Object> map,
		String parentKey) {
	if (null == nodeMap || nodeMap.getLength() < 1) {
		return;
	}
	for (int i = 0; i < nodeMap.getLength(); i++) {
		Node node = nodeMap.item(i);
		if (null == node) {
			continue;
		}
		if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
			if (StringUtils.isEmpty(node.getNodeName())) {
				continue;
			}
			if (StringUtils.isEmpty(node.getNodeValue())) {
				continue;
			}
			map.put(String.join(DOT, parentKey, node.getNodeName()),
					node.getNodeValue());
		}
	}
}
 
Example 3
Source File: DOMXPathTransform.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void unmarshalParams(Element paramsElem) {
    String xPath = paramsElem.getFirstChild().getNodeValue();
    // create a Map of namespace prefixes
    NamedNodeMap attributes = paramsElem.getAttributes();
    if (attributes != null) {
        int length = attributes.getLength();
        Map<String, String> namespaceMap =
            new HashMap<String, String>(length);
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr)attributes.item(i);
            String prefix = attr.getPrefix();
            if (prefix != null && prefix.equals("xmlns")) {
                namespaceMap.put(attr.getLocalName(), attr.getValue());
            }
        }
        this.params = new XPathFilterParameterSpec(xPath, namespaceMap);
    } else {
        this.params = new XPathFilterParameterSpec(xPath);
    }
}
 
Example 4
Source File: EndPositionFinderVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Element e) {
        position += getElementStartTokenLength(e, true); //open start tag
        NamedNodeMap attrs = e.getAttributes();
        for(int i = 0; i < attrs.getLength(); i++){
            Node attr = (Node)attrs.item(i);
            attr.accept(this);
            if(found) {
                return;
        }
        }
        position += getStartTagWhiteSpaceTokensLength(e); //all whitespaces
        position++; //close of start tag
        NodeList children = e.getChildNodes();
        for(int i = 0; i < children.getLength(); i++){
            Node n = (Node)children.item(i);
            n.accept(this);
            if(found) {
                return;
        }
        }
        position += getElementStartTokenLength(e, false); //open end tag
        position += getEndTagWhiteSpaceTokensLength(e); //all whitespaces
        position++; //close of end tag

    if(e.getId() == node.getId()){
        found = true;
    }
}
 
Example 5
Source File: DOMWriter.java    From olat with Apache License 2.0 5 votes vote down vote up
/** Returns a sorted list of attributes. */
protected Attr[] sortAttributes(NamedNodeMap attrs) {

    int len = (attrs != null) ? attrs.getLength() : 0;
    Attr array[] = new Attr[len];
    for (int i = 0; i < len; i++) {
        array[i] = (Attr) attrs.item(i);
    }
    for (int i = 0; i < len - 1; i++) {
        String name = array[i].getNodeName();
        int index = i;
        for (int j = i + 1; j < len; j++) {
            String curName = array[j].getNodeName();
            if (curName.compareTo(name) < 0) {
                name = curName;
                index = j;
            }
        }
        if (index != i) {
            Attr temp = array[i];
            array[i] = array[index];
            array[index] = temp;
        }
    }

    return (array);

}
 
Example 6
Source File: XmlUtils.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private static Attributes namedNodeMapToSaxAttributes(final NamedNodeMap attributesMap,
        final Map<Integer, List<String>> attributesOrderMap, final Node element) {
    final AttributesImpl attributes = new AttributesImpl();
    final int length = attributesMap.getLength();
    for (int i = 0; i < length; i++) {
        final int orderedIndex = getIndex(attributesMap, attributesOrderMap, element, i);
        final Node attr = attributesMap.item(orderedIndex);
        attributes.addAttribute(attr.getNamespaceURI(), attr.getLocalName(),
            attr.getNodeName(), null, attr.getNodeValue());
    }

    return attributes;
}
 
Example 7
Source File: DOMUtil.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static Attr[] getAttrs(Element elem) {
    NamedNodeMap attrMap = elem.getAttributes();
    Attr [] attrArray = new Attr[attrMap.getLength()];
    for (int i=0; i<attrMap.getLength(); i++)
        attrArray[i] = (Attr)attrMap.item(i);
    return attrArray;
}
 
Example 8
Source File: SAAJMessage.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the Attributes that are not namesapce declarations
 * @param attrs
 * @return
 */
private AttributesImpl getAttributes(NamedNodeMap attrs) {
    AttributesImpl atts = new AttributesImpl();
    if(attrs == null)
        return EMPTY_ATTS;
    for(int i=0; i < attrs.getLength();i++) {
        Attr a = (Attr)attrs.item(i);
        //check if attr is ns declaration
        if("xmlns".equals(a.getPrefix()) || "xmlns".equals(a.getLocalName())) {
          continue;
        }
        atts.addAttribute(fixNull(a.getNamespaceURI()),a.getLocalName(),a.getName(),a.getSchemaTypeInfo().getTypeName(),a.getValue());
    }
    return atts;
}
 
Example 9
Source File: ChartPanel.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param node
 * @param attributeName - name of child node to return
 * @return Node
 */
private Node getAttributeByName(Node node, String attributeName) {
    if (node == null) {
        return null;
    }
    NamedNodeMap nnm = node.getAttributes();
    for (int i = 0; i < nnm.getLength(); i++) {
        Node n = nnm.item(i);
        if (n.getNodeName().equals(attributeName)) {
            return n;
        }
    }
    return null; // no such attribute was found
}
 
Example 10
Source File: StaxSerializer.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean addNamespaces(XMLStreamReader reader, Node ctx) {
    try {
        NamespaceContext nsctx = reader.getNamespaceContext();
        if (nsctx instanceof com.ctc.wstx.sr.InputElementStack) {
            com.ctc.wstx.sr.InputElementStack ies = (com.ctc.wstx.sr.InputElementStack)nsctx;
            com.ctc.wstx.util.InternCache ic = com.ctc.wstx.util.InternCache.getInstance();

            Map<String, String> storedNamespaces = new HashMap<>();
            Node wk = ctx;
            while (wk != null) {
                NamedNodeMap atts = wk.getAttributes();
                if (atts != null) {
                    for (int i = 0; i < atts.getLength(); ++i) {
                        Node att = atts.item(i);
                        String nodeName = att.getNodeName();
                        if (("xmlns".equals(nodeName) || nodeName.startsWith("xmlns:"))
                            && !storedNamespaces.containsKey(att.getNodeName())) {

                            String prefix = att.getLocalName();
                            if ("xmlns".equals(prefix)) {
                                prefix = "";
                            }
                            prefix = ic.intern(prefix);
                            ies.addNsBinding(prefix, att.getNodeValue());
                            storedNamespaces.put(nodeName, att.getNodeValue());
                        }
                    }
                }
                wk = wk.getParentNode();
            }
        }
        return true;
    } catch (Throwable t) {
        //ignore, not much we can do but hope the decrypted XML is stand alone ok
    }
    return false;
}
 
Example 11
Source File: WbmpDefaultImageMetadataTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
void displayMetadata(Node node, int level) {
    indent(level); // emit open tag
    System.out.print("<" + node.getNodeName());
    NamedNodeMap map = node.getAttributes();
    if (map != null) { // print attribute values
        int length = map.getLength();
        for (int i = 0; i < length; i++) {
            Node attr = map.item(i);
            System.out.print(" " + attr.getNodeName() +
                             "=\"" + attr.getNodeValue() + "\"");
        }
    }
    Node child = node.getFirstChild();

    if (node.getNodeValue() != null && !node.getNodeValue().equals("") ) {
        System.out.println(">");
        indent(level);
        System.out.println(node.getNodeValue());
        indent(level); // emit close tag
        System.out.println("</" + node.getNodeName() + ">");
    } else  if (child != null) {
        System.out.println(">"); // close current tag
        while (child != null) { // emit child tags recursively
            displayMetadata(child, level + 1);
            child = child.getNextSibling();
        }
        indent(level); // emit close tag
        System.out.println("</" + node.getNodeName() + ">");
    } else {
        System.out.println("/>");
    }
}
 
Example 12
Source File: DOMWriter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Returns a sorted list of attributes.
 * @param attrs The map to sort
 * @return a sorted attribute array
 *
 * @deprecated Will be made private in Tomcat 9.
 */
@Deprecated
protected Attr[] sortAttributes(NamedNodeMap attrs) {
    if (attrs == null) {
        return new Attr[0];
    }

    int len = attrs.getLength();
    Attr array[] = new Attr[len];
    for (int i = 0; i < len; i++) {
        array[i] = (Attr) attrs.item(i);
    }
    for (int i = 0; i < len - 1; i++) {
        String name = null;
        name = array[i].getLocalName();
        int index = i;
        for (int j = i + 1; j < len; j++) {
            String curName = null;
            curName = array[j].getLocalName();
            if (curName.compareTo(name) < 0) {
                name = curName;
                index = j;
            }
        }
        if (index != i) {
            Attr temp = array[i];
            array[i] = array[index];
            array[index] = temp;
        }
    }

    return array;
}
 
Example 13
Source File: DOM2DTMdefaultNamespaceDeclarationNode.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/**
     * DOM Level 3 - Experimental:
     * Look up the namespace URI associated to the given prefix, starting from this node.
     * Use lookupNamespaceURI(null) to lookup the default namespace
     *
     * @param namespaceURI
     * @return th URI for the namespace
     * @since DOM Level 3
     */
    public String lookupNamespaceURI(String specifiedPrefix) {
        short type = this.getNodeType();
        switch (type) {
        case Node.ELEMENT_NODE : {

                String namespace = this.getNamespaceURI();
                String prefix = this.getPrefix();
                if (namespace !=null) {
                    // REVISIT: is it possible that prefix is empty string?
                    if (specifiedPrefix== null && prefix==specifiedPrefix) {
                        // looking for default namespace
                        return namespace;
                    } else if (prefix != null && prefix.equals(specifiedPrefix)) {
                        // non default namespace
                        return namespace;
                    }
                }
                if (this.hasAttributes()) {
                    NamedNodeMap map = this.getAttributes();
                    int length = map.getLength();
                    for (int i=0;i<length;i++) {
                        Node attr = map.item(i);
                        String attrPrefix = attr.getPrefix();
                        String value = attr.getNodeValue();
                        namespace = attr.getNamespaceURI();
                        if (namespace !=null && namespace.equals("http://www.w3.org/2000/xmlns/")) {
                            // at this point we are dealing with DOM Level 2 nodes only
                            if (specifiedPrefix == null &&
                                attr.getNodeName().equals("xmlns")) {
                                // default namespace
                                return value;
                            } else if (attrPrefix !=null &&
                                       attrPrefix.equals("xmlns") &&
                                       attr.getLocalName().equals(specifiedPrefix)) {
                 // non default namespace
                                return value;
                            }
                        }
                    }
                }
                /*
                NodeImpl ancestor = (NodeImpl)getElementAncestor(this);
                if (ancestor != null) {
                    return ancestor.lookupNamespaceURI(specifiedPrefix);
                }
                */

                return null;


            }
/*
        case Node.DOCUMENT_NODE : {
                return((NodeImpl)((Document)this).getDocumentElement()).lookupNamespaceURI(specifiedPrefix) ;
            }
*/
        case Node.ENTITY_NODE :
        case Node.NOTATION_NODE:
        case Node.DOCUMENT_FRAGMENT_NODE:
        case Node.DOCUMENT_TYPE_NODE:
            // type is unknown
            return null;
        case Node.ATTRIBUTE_NODE:{
                if (this.getOwnerElement().getNodeType() == Node.ELEMENT_NODE) {
                    return getOwnerElement().lookupNamespaceURI(specifiedPrefix);

                }
                return null;
            }
        default:{
           /*
                NodeImpl ancestor = (NodeImpl)getElementAncestor(this);
                if (ancestor != null) {
                    return ancestor.lookupNamespaceURI(specifiedPrefix);
                }
             */
                return null;
            }

        }
    }
 
Example 14
Source File: DOMXPathFilter2Transform.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private void unmarshalParams(Element curXPathElem) throws MarshalException
{
    List<XPathType> list = new ArrayList<XPathType>();
    while (curXPathElem != null) {
        String xPath = curXPathElem.getFirstChild().getNodeValue();
        String filterVal = DOMUtils.getAttributeValue(curXPathElem,
                                                      "Filter");
        if (filterVal == null) {
            throw new MarshalException("filter cannot be null");
        }
        XPathType.Filter filter = null;
        if (filterVal.equals("intersect")) {
            filter = XPathType.Filter.INTERSECT;
        } else if (filterVal.equals("subtract")) {
            filter = XPathType.Filter.SUBTRACT;
        } else if (filterVal.equals("union")) {
            filter = XPathType.Filter.UNION;
        } else {
            throw new MarshalException("Unknown XPathType filter type" +
                                       filterVal);
        }
        NamedNodeMap attributes = curXPathElem.getAttributes();
        if (attributes != null) {
            int length = attributes.getLength();
            Map<String, String> namespaceMap =
                new HashMap<String, String>(length);
            for (int i = 0; i < length; i++) {
                Attr attr = (Attr)attributes.item(i);
                String prefix = attr.getPrefix();
                if (prefix != null && prefix.equals("xmlns")) {
                    namespaceMap.put(attr.getLocalName(), attr.getValue());
                }
            }
            list.add(new XPathType(xPath, filter, namespaceMap));
        } else {
            list.add(new XPathType(xPath, filter));
        }

        curXPathElem = DOMUtils.getNextSiblingElement(curXPathElem);
    }
    this.params = new XPathFilter2ParameterSpec(list);
}
 
Example 15
Source File: UnImplNode.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
     * DOM Level 3 - Experimental:
     * Look up the namespace URI associated to the given prefix, starting from this node.
     * Use lookupNamespaceURI(null) to lookup the default namespace
     *
     * @param namespaceURI
     * @return th URI for the namespace
     * @since DOM Level 3
     */
    public String lookupNamespaceURI(String specifiedPrefix) {
        short type = this.getNodeType();
        switch (type) {
        case Node.ELEMENT_NODE : {

                String namespace = this.getNamespaceURI();
                String prefix = this.getPrefix();
                if (namespace !=null) {
                    // REVISIT: is it possible that prefix is empty string?
                    if (specifiedPrefix== null && prefix==specifiedPrefix) {
                        // looking for default namespace
                        return namespace;
                    } else if (prefix != null && prefix.equals(specifiedPrefix)) {
                        // non default namespace
                        return namespace;
                    }
                }
                if (this.hasAttributes()) {
                    NamedNodeMap map = this.getAttributes();
                    int length = map.getLength();
                    for (int i=0;i<length;i++) {
                        Node attr = map.item(i);
                        String attrPrefix = attr.getPrefix();
                        String value = attr.getNodeValue();
                        namespace = attr.getNamespaceURI();
                        if (namespace !=null && namespace.equals("http://www.w3.org/2000/xmlns/")) {
                            // at this point we are dealing with DOM Level 2 nodes only
                            if (specifiedPrefix == null &&
                                attr.getNodeName().equals("xmlns")) {
                                // default namespace
                                return value;
                            } else if (attrPrefix !=null &&
                                       attrPrefix.equals("xmlns") &&
                                       attr.getLocalName().equals(specifiedPrefix)) {
                 // non default namespace
                                return value;
                            }
                        }
                    }
                }
                /*
                NodeImpl ancestor = (NodeImpl)getElementAncestor(this);
                if (ancestor != null) {
                    return ancestor.lookupNamespaceURI(specifiedPrefix);
                }
                */

                return null;


            }
/*
        case Node.DOCUMENT_NODE : {
                return((NodeImpl)((Document)this).getDocumentElement()).lookupNamespaceURI(specifiedPrefix) ;
            }
*/
        case Node.ENTITY_NODE :
        case Node.NOTATION_NODE:
        case Node.DOCUMENT_FRAGMENT_NODE:
        case Node.DOCUMENT_TYPE_NODE:
            // type is unknown
            return null;
        case Node.ATTRIBUTE_NODE:{
                if (this.getOwnerElement().getNodeType() == Node.ELEMENT_NODE) {
                    return getOwnerElement().lookupNamespaceURI(specifiedPrefix);

                }
                return null;
            }
        default:{
           /*
                NodeImpl ancestor = (NodeImpl)getElementAncestor(this);
                if (ancestor != null) {
                    return ancestor.lookupNamespaceURI(specifiedPrefix);
                }
             */
                return null;
            }

        }
    }
 
Example 16
Source File: Canonicalizer20010315.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns the Attr[]s to be output for the given element.
 * <br>
 * The code of this method is a copy of {@link #handleAttributes(Element,
 * NameSpaceSymbTable)},
 * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
 * So if the element in question isRoot of c14n, it's parent is not in the
 * node set, as well as all other ancestors.
 *
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
    throws CanonicalizationException {
    if (!element.hasAttributes() && !firstCall) {
        return null;
    }
    // result will contain the attrs which have to be output
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                //It's not a namespace attr node. Add to the result and continue.
                result.add(attribute);
            } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
                //The default mapping for xml must not be output.
                Node n = ns.addMappingAndRender(NName, NValue, attribute);

                if (n != null) {
                    //Render the ns definition
                    result.add((Attr)n);
                    if (C14nHelper.namespaceIsRelative(attribute)) {
                        Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
                        throw new CanonicalizationException(
                            "c14n.Canonicalizer.RelativeNamespace", exArgs
                        );
                    }
                }
            }
        }
    }

    if (firstCall) {
        //It is the first node of the subtree
        //Obtain all the namespaces defined in the parents, and added to the output.
        ns.getUnrenderedNodes(result);
        //output the attributes in the xml namespace.
        xmlattrStack.getXmlnsAttr(result);
        firstCall = false;
    }

    return result.iterator();
}
 
Example 17
Source File: TreeWalker.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * End processing of given node
 *
 *
 * @param node Node we just finished processing
 *
 * @throws org.xml.sax.SAXException
 */
protected void endNode(Node node) throws org.xml.sax.SAXException
{

  switch (node.getNodeType())
  {
  case Node.DOCUMENT_NODE :
    break;

  case Node.ELEMENT_NODE :
    String ns = m_dh.getNamespaceOfNode(node);
    if(null == ns)
      ns = "";
    this.m_contentHandler.endElement(ns,
                                       m_dh.getLocalNameOfNode(node),
                                       node.getNodeName());

    NamedNodeMap atts = ((Element) node).getAttributes();
    int nAttrs = atts.getLength();

    for (int i = 0; i < nAttrs; i++)
    {
      Node attr = atts.item(i);
      String attrName = attr.getNodeName();

      if (attrName.equals("xmlns") || attrName.startsWith("xmlns:"))
      {
        int index;
        // Use "" instead of null, as Xerces likes "" for the
        // name of the default namespace.  Fix attributed
        // to "Steven Murray" <[email protected]>.
        String prefix = (index = attrName.indexOf(":")) < 0
                        ? "" : attrName.substring(index + 1);

        this.m_contentHandler.endPrefixMapping(prefix);
      }
    }
    break;
  case Node.CDATA_SECTION_NODE :
    break;
  case Node.ENTITY_REFERENCE_NODE :
  {
    EntityReference eref = (EntityReference) node;

    if (m_contentHandler instanceof LexicalHandler)
    {
      LexicalHandler lh = ((LexicalHandler) this.m_contentHandler);

      lh.endEntity(eref.getNodeName());
    }
  }
  break;
  default :
  }
}
 
Example 18
Source File: NamespaceContextImpl.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public String getNamespaceURI(String prefix) {
    Node parent = e;
    String namespace = null;

    if (prefix.equals("xml")) {
        namespace = WellKnownNamespace.XML_NAMESPACE_URI;
    } else {
        int type;

        while ((null != parent) && (null == namespace)
                && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
                || (type == Node.ENTITY_REFERENCE_NODE))) {
            if (type == Node.ELEMENT_NODE) {
                if (parent.getNodeName().indexOf(prefix + ':') == 0)
                    return parent.getNamespaceURI();
                NamedNodeMap nnm = parent.getAttributes();

                for (int i = 0; i < nnm.getLength(); i++) {
                    Node attr = nnm.item(i);
                    String aname = attr.getNodeName();
                    boolean isPrefix = aname.startsWith("xmlns:");

                    if (isPrefix || aname.equals("xmlns")) {
                        int index = aname.indexOf(':');
                        String p = isPrefix ? aname.substring(index + 1) : "";

                        if (p.equals(prefix)) {
                            namespace = attr.getNodeValue();

                            break;
                        }
                    }
                }
            }

            parent = parent.getParentNode();
        }
    }

    return namespace;
}
 
Example 19
Source File: XMLUtils.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * This method is a tree-search to help prevent against wrapping attacks. It checks that no
 * two Elements have ID Attributes that match the "value" argument, if this is the case then
 * "false" is returned. Note that a return value of "true" does not necessarily mean that
 * a matching Element has been found, just that no wrapping attack has been detected.
 */
public static boolean protectAgainstWrappingAttack(Node startNode, String value) {
    Node startParent = startNode.getParentNode();
    Node processedNode = null;
    Element foundElement = null;

    String id = value.trim();
    if (!id.isEmpty() && id.charAt(0) == '#') {
        id = id.substring(1);
    }

    while (startNode != null) {
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;

            NamedNodeMap attributes = se.getAttributes();
            if (attributes != null) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attr = (Attr)attributes.item(i);
                    if (attr.isId() && id.equals(attr.getValue())) {
                        if (foundElement == null) {
                            // Continue searching to find duplicates
                            foundElement = attr.getOwnerElement();
                        } else {
                            log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
                            return false;
                        }
                    }
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }

        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return true;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return true;
}
 
Example 20
Source File: CoTDetailsDeff.java    From defense-solutions-proofs-of-concept with Apache License 2.0 4 votes vote down vote up
public static String elementToString(Node n) {

		String name = n.getNodeName();
		short type = n.getNodeType();

		if (Node.CDATA_SECTION_NODE == type) {
			return "<![CDATA[" + n.getNodeValue() + "]]&gt;";
		}

		if (name.startsWith("#")) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		sb.append('<').append(name);

		NamedNodeMap attrs = n.getAttributes();
		if (attrs != null) {
			for (int i = 0; i < attrs.getLength(); i++) {
				Node attr = attrs.item(i);
				sb.append(' ').append(attr.getNodeName()).append("=\"")
				.append(attr.getNodeValue()).append("\"");
			}
		}

		String textContent = null;
		NodeList children = n.getChildNodes();

		if (children.getLength() == 0) {
			if ((textContent = n.getTextContent()) != null
					&& !"".equals(textContent)) {
				sb.append(textContent).append("</").append(name).append('>');
			} else {
				sb.append("/>").append('\n');
			}
		} else {
			sb.append('>').append('\n');
			boolean hasValidChildren = false;
			for (int i = 0; i < children.getLength(); i++) {
				String childToString = elementToString(children.item(i));
				if (!"".equals(childToString)) {
					sb.append(childToString);
					hasValidChildren = true;
				}
			}

			if (!hasValidChildren
					&& ((textContent = n.getTextContent()) != null)) {
				sb.append(textContent);
			}

			sb.append("</").append(name).append('>');
		}

		return sb.toString();
	}