Java Code Examples for org.w3c.dom.Attr#getNodeValue()

The following examples show how to use org.w3c.dom.Attr#getNodeValue() . 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: WadlModeler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Node findMethodNodeByRef(Node doc, String ref) throws XPathExpressionException {
    Node method = null;
    NodeList methods = RestUtils.getNodeList(doc, "//application/method");
    if (methods != null && methods.getLength() > 0) {
        for (int j = 0; j < methods.getLength(); j++) {
            method = methods.item(j);
            NamedNodeMap mAttrList = method.getAttributes();
            Attr idAttr = (Attr) mAttrList.getNamedItem("id");
            if (idAttr != null) {
                String mName = idAttr.getNodeValue();
                if (mName.equals(ref)) {
                    return method;
                }
            }
        }
    }
    return method;
}
 
Example 2
Source File: SimpleNamespaceResolver.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Defines if this visitor should process the provided node.
 *
 * @param aNode The DOM node to process.
 * @return <code>true</code> if the provided Node should be processed by this NodeProcessor.
 */
public boolean accept(final Node aNode) {

    // Correct namespace?
    if (aNode.getNamespaceURI() != null
            && XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(aNode.getNamespaceURI())) {
        return true;
    }

    // Is this Node the targetNamespace attribute?
    if (aNode instanceof Attr) {

        final Attr attribute = (Attr) aNode;
        final Element parent = attribute.getOwnerElement();
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI())
                && SCHEMA.equalsIgnoreCase(parent.getLocalName())
                && TARGET_NAMESPACE.equals(attribute.getLocalName())) {

            SimpleNamespaceResolver.this.localNamespaceURI = attribute.getNodeValue();
        }
    }

    // Ignore processing this Node.
    return false;
}
 
Example 3
Source File: WadlModeler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getAttributeValue(Node attr, String name) {
    NamedNodeMap mAttrList = attr.getAttributes();
    Attr refAttr = (Attr) mAttrList.getNamedItem(name);
    if (refAttr != null) {
        return refAttr.getNodeValue();
    }
    return null;
}
 
Example 4
Source File: LogHeaderDefinition.java    From jlibs with Apache License 2.0 5 votes vote down vote up
public static LogHeaderDefinition parse(File file) throws Exception{
    Element root = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file).getDocumentElement();
    NodeList nodeList = root.getElementsByTagName("pattern");
    if(nodeList.getLength()==0)
        throw new IllegalArgumentException("[LogHeader] pattern element is missing");
    String p = nodeList.item(0).getTextContent();
    Pattern pattern;
    try{
        pattern = Pattern.compile(p);
    }catch(PatternSyntaxException ex){
        throw new RuntimeException("[LogHeader] invalid regex in pattern element", ex);
    }
    String groupNames[] = new String[pattern.matcher("").groupCount()+1];
    groupNames[0] = "header";
    NodeList groupList = root.getElementsByTagName("field");
    for(int i=0; i<groupList.getLength(); i++){
        Element groupElement = (Element)groupList.item(i);
        Attr attr = groupElement.getAttributeNode("group");
        if(attr==null)
            throw new IllegalArgumentException("[LogHeader] group attribute missing in field element");
        int index = Integer.parseInt(attr.getNodeValue());
        attr = groupElement.getAttributeNode("name");
        if(attr==null)
            throw new IllegalArgumentException("[LogHeader] name attribute missing in field element");
        String name = attr.getNodeValue();
        if(name.equals("header"))
            throw new IllegalArgumentException("[LogHeader] field name header is reserved");
        groupNames[index] = name;
    }
    if(groupNames[groupNames.length-1]==null)
        throw new IllegalArgumentException("[LogHeader] expected "+(groupNames.length-1)+" field elements");
    return new LogHeaderDefinition(pattern, groupNames);
}
 
Example 5
Source File: XMLCipher.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param uri
 */
public CipherReferenceImpl(Attr uri) {
    referenceURI = uri.getNodeValue();
    referenceNode = uri;
}
 
Example 6
Source File: Canonicalizer11.java    From JDKSourceCode1.8 with MIT License 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 7
Source File: XMLCipher.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param uri
 */
public CipherReferenceImpl(Attr uri) {
    referenceURI = uri.getNodeValue();
    referenceNode = uri;
}
 
Example 8
Source File: Canonicalizer20010315.java    From openjdk-8 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 9
Source File: Canonicalizer20010315.java    From JDKSourceCode1.8 with MIT License 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 10
Source File: Canonicalizer20010315.java    From jdk8u60 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 11
Source File: XmlUtils.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
private static DomNode createFrom(final SgmlPage page, final Node source, final boolean handleXHTMLAsHTML,
        final Map<Integer, List<String>> attributesOrderMap) {
    if (source.getNodeType() == Node.TEXT_NODE) {
        return new DomText(page, source.getNodeValue());
    }
    if (source.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        return new DomProcessingInstruction(page, source.getNodeName(), source.getNodeValue());
    }
    if (source.getNodeType() == Node.COMMENT_NODE) {
        return new DomComment(page, source.getNodeValue());
    }
    if (source.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
        final DocumentType documentType = (DocumentType) source;
        return new DomDocumentType(page, documentType.getName(), documentType.getPublicId(),
                documentType.getSystemId());
    }
    final String ns = source.getNamespaceURI();
    String localName = source.getLocalName();
    if (handleXHTMLAsHTML && Html.XHTML_NAMESPACE.equals(ns)) {
        final ElementFactory factory = page.getWebClient().getPageCreator().getHtmlParser().getFactory(localName);
        return factory.createElementNS(page, ns, localName,
                namedNodeMapToSaxAttributes(source.getAttributes(), attributesOrderMap, source));
    }
    final NamedNodeMap nodeAttributes = source.getAttributes();
    if (page != null && page.isHtmlPage()) {
        localName = localName.toUpperCase(Locale.ROOT);
    }
    final String qualifiedName;
    if (source.getPrefix() == null) {
        qualifiedName = localName;
    }
    else {
        qualifiedName = source.getPrefix() + ':' + localName;
    }

    final String namespaceURI = source.getNamespaceURI();
    if (Html.SVG_NAMESPACE.equals(namespaceURI)) {
        return page.getWebClient().getPageCreator().getHtmlParser().getSvgFactory()
                .createElementNS(page, namespaceURI, qualifiedName,
                        namedNodeMapToSaxAttributes(nodeAttributes, attributesOrderMap, source));
    }

    final Map<String, DomAttr> attributes = new LinkedHashMap<>();
    for (int i = 0; i < nodeAttributes.getLength(); i++) {
        final int orderedIndex = getIndex(nodeAttributes, attributesOrderMap, source, i);
        final Attr attribute = (Attr) nodeAttributes.item(orderedIndex);
        final String attributeNamespaceURI = attribute.getNamespaceURI();
        final String attributeQualifiedName;
        if (attribute.getPrefix() != null) {
            attributeQualifiedName = attribute.getPrefix() + ':' + attribute.getLocalName();
        }
        else {
            attributeQualifiedName = attribute.getLocalName();
        }
        final String value = attribute.getNodeValue();
        final boolean specified = attribute.getSpecified();
        final DomAttr xmlAttribute =
                new DomAttr(page, attributeNamespaceURI, attributeQualifiedName, value, specified);
        attributes.put(attribute.getNodeName(), xmlAttribute);
    }
    return new DomElement(namespaceURI, qualifiedName, page, attributes);
}
 
Example 12
Source File: Canonicalizer20010315.java    From jdk8u-jdk 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 13
Source File: DOMUtil.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 14
Source File: DOMHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Given an XML Namespace prefix and a context in which the prefix
 * is to be evaluated, return the Namespace Name this prefix was
 * bound to. Note that DOM Level 3 is expected to provide a version of
 * this which deals with the DOM's "early binding" behavior.
 *
 * Default handling:
 *
 * @param prefix String containing namespace prefix to be resolved,
 * without the ':' which separates it from the localname when used
 * in a Node Name. The empty sting signifies the default namespace
 * at this point in the document.
 * @param namespaceContext Element which provides context for resolution.
 * (We could extend this to work for other nodes by first seeking their
 * nearest Element ancestor.)
 *
 * @return a String containing the Namespace URI which this prefix
 * represents in the specified context.
 */
public String getNamespaceForPrefix(String prefix, Element namespaceContext)
{

  int type;
  Node parent = namespaceContext;
  String namespace = null;

  if (prefix.equals("xml"))
  {
    namespace = QName.S_XMLNAMESPACEURI; // Hardcoded, per Namespace spec
  }
      else if(prefix.equals("xmlns"))
  {
        // Hardcoded in the DOM spec, expected to be adopted by
        // Namespace spec. NOTE: Namespace declarations _must_ use
        // the xmlns: prefix; other prefixes declared as belonging
        // to this namespace will not be recognized and should
        // probably be rejected by parsers as erroneous declarations.
    namespace = "http://www.w3.org/2000/xmlns/";
  }
  else
  {
        // Attribute name for this prefix's declaration
        String declname=(prefix=="")
                      ? "xmlns"
                      : "xmlns:"+prefix;

        // Scan until we run out of Elements or have resolved the namespace
    while ((null != parent) && (null == namespace)
           && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
               || (type == Node.ENTITY_REFERENCE_NODE)))
    {
      if (type == Node.ELEMENT_NODE)
      {

                      // Look for the appropriate Namespace Declaration attribute,
                      // either "xmlns:prefix" or (if prefix is "") "xmlns".
                      // TODO: This does not handle "implicit declarations"
                      // which may be created when the DOM is edited. DOM Level
                      // 3 will define how those should be interpreted. But
                      // this issue won't arise in freshly-parsed DOMs.

              // NOTE: declname is set earlier, outside the loop.
                      Attr attr=((Element)parent).getAttributeNode(declname);
                      if(attr!=null)
                      {
              namespace = attr.getNodeValue();
              break;
                      }
              }

      parent = getParentOfNode(parent);
    }
  }

  return namespace;
}
 
Example 15
Source File: DOMUtil.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 16
Source File: DOMUtil.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 17
Source File: ManifestMerger.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Extracts the fully qualified class names from the manifest and uses the
 * prefix notation relative to the manifest package. This basically reverses
 * the effects of {@link #expandFqcns(Document)}, though of course it may
 * also remove prefixes which were inlined in the original documents.
 *
 * @param doc the document in which to extract the FQCNs.
 */
private void extractFqcns(Document doc) {
    // Find the package attribute of the manifest.
    String pkg = null;
    Element manifest = findFirstElement(doc, "/manifest");
    if (manifest != null) {
        pkg = manifest.getAttribute("package");
    }

    if (pkg == null || pkg.isEmpty()) {
        return;
    }

    int pkgLength = pkg.length();
    for (String elementAttr : sClassAttributes) {
        String[] names = elementAttr.split("/");
        if (names.length != 2) {
            continue;
        }
        String elemName = names[0];
        String attrName = names[1];
        NodeList elements = doc.getElementsByTagName(elemName);
        for (int i = 0; i < elements.getLength(); i++) {
            Node elem = elements.item(i);
            if (elem instanceof Element) {
                Attr attr = ((Element) elem).getAttributeNodeNS(NS_URI, attrName);
                if (attr != null) {
                    String value = attr.getNodeValue();

                    // We know it's a shortened FQCN if it starts with a dot
                    // or does not contain any dot.
                    if (value != null && value.length() > pkgLength &&
                            value.startsWith(pkg) && value.charAt(pkgLength) == '.') {
                        value = value.substring(pkgLength);
                        attr.setNodeValue(value);
                    }
                }
            }
        }
    }
}
 
Example 18
Source File: XMLCipher.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param uri
 */
public CipherReferenceImpl(Attr uri) {
    referenceURI = uri.getNodeValue();
    referenceNode = uri;
}
 
Example 19
Source File: DOMHelper.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Given an XML Namespace prefix and a context in which the prefix
 * is to be evaluated, return the Namespace Name this prefix was 
 * bound to. Note that DOM Level 3 is expected to provide a version of
 * this which deals with the DOM's "early binding" behavior.
 * 
 * Default handling:
 *
 * @param prefix String containing namespace prefix to be resolved, 
 * without the ':' which separates it from the localname when used 
 * in a Node Name. The empty sting signifies the default namespace
 * at this point in the document.
 * @param namespaceContext Element which provides context for resolution.
 * (We could extend this to work for other nodes by first seeking their
 * nearest Element ancestor.)
 *
 * @return a String containing the Namespace URI which this prefix
 * represents in the specified context.
 */
public String getNamespaceForPrefix(String prefix, Element namespaceContext)
{

  int type;
  Node parent = namespaceContext;
  String namespace = null;

  if (prefix.equals("xml"))
  {
    namespace = QName.S_XMLNAMESPACEURI; // Hardcoded, per Namespace spec
  }
      else if(prefix.equals("xmlns"))
  {
        // Hardcoded in the DOM spec, expected to be adopted by
        // Namespace spec. NOTE: Namespace declarations _must_ use
        // the xmlns: prefix; other prefixes declared as belonging
        // to this namespace will not be recognized and should
        // probably be rejected by parsers as erroneous declarations.
    namespace = "http://www.w3.org/2000/xmlns/"; 
  }
  else
  {
        // Attribute name for this prefix's declaration
        String declname=(prefix=="")
                      ? "xmlns"
                      : "xmlns:"+prefix;
                                         
        // Scan until we run out of Elements or have resolved the namespace
    while ((null != parent) && (null == namespace)
           && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
               || (type == Node.ENTITY_REFERENCE_NODE)))
    {
      if (type == Node.ELEMENT_NODE)
      {
                      
                      // Look for the appropriate Namespace Declaration attribute,
                      // either "xmlns:prefix" or (if prefix is "") "xmlns".
                      // TODO: This does not handle "implicit declarations"
                      // which may be created when the DOM is edited. DOM Level
                      // 3 will define how those should be interpreted. But
                      // this issue won't arise in freshly-parsed DOMs.
                      
              // NOTE: declname is set earlier, outside the loop.
                      Attr attr=((Element)parent).getAttributeNode(declname);
                      if(attr!=null)
                      {
              namespace = attr.getNodeValue();
              break;
                      }
              }

      parent = getParentOfNode(parent);
    }
  }

  return namespace;
}
 
Example 20
Source File: XMLCipher.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * @param uri
 */
public CipherReferenceImpl(Attr uri) {
    referenceURI = uri.getNodeValue();
    referenceNode = uri;
}