Java Code Examples for org.w3c.dom.Node#ENTITY_REFERENCE_NODE

The following examples show how to use org.w3c.dom.Node#ENTITY_REFERENCE_NODE . 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: AttrImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Override default behavior so that if deep is true, children are also
 * toggled.
 * @see Node
 * <P>
 * Note: this will not change the state of an EntityReference or its
 * children, which are always read-only.
 */
public void setReadOnly(boolean readOnly, boolean deep) {

    super.setReadOnly(readOnly, deep);

    if (deep) {

        if (needsSyncChildren()) {
            synchronizeChildren();
        }

        if (hasStringValue()) {
            return;
        }
        // Recursively set kids
        for (ChildNode mykid = (ChildNode) value;
             mykid != null;
             mykid = mykid.nextSibling) {
            if (mykid.getNodeType() != Node.ENTITY_REFERENCE_NODE) {
                mykid.setReadOnly(readOnly,true);
            }
        }
    }
}
 
Example 2
Source File: DOM3TreeWalker.java    From openjdk-jdk9 with GNU General Public License v2.0 6 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.DOCUMENT_TYPE_NODE :
            serializeDocType((DocumentType) node, false);
            break;
        case Node.ELEMENT_NODE :
            serializeElement((Element) node, false);
            break;
        case Node.CDATA_SECTION_NODE :
            break;
        case Node.ENTITY_REFERENCE_NODE :
            serializeEntityReference((EntityReference) node, false);
            break;
        default :
            }
}
 
Example 3
Source File: DOMUtilities.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * extracts all text-elements of a particular element and returns an single string containing the contents of all
 * textelements and all character entity nodes. If a node is not known to the parser, its string value will be
 * delivered as <code>&entityname;</code>.
 *
 * @param e the element which is direct parent of all to be extracted textnodes.
 * @return the extracted String
 */
public static String getText( final Element e ) {
  final NodeList nl = e.getChildNodes();
  final StringBuilder result = new StringBuilder( 100 );

  for ( int i = 0; i < nl.getLength(); i++ ) {
    final Node n = nl.item( i );
    if ( n.getNodeType() == Node.TEXT_NODE ) {
      final Text text = (Text) n;

      result.append( text.getData() );
    } else if ( n.getNodeType() == Node.ENTITY_REFERENCE_NODE ) {
      result.append( '&' );
      result.append( n.getNodeName() );
      result.append( ';' );
    }
  }
  return XML_ENTITIES.decodeEntities( result.toString() );
}
 
Example 4
Source File: DOMPrinter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void print(Node node) throws XMLStreamException {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
        visitDocument((Document) node);
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        visitDocumentFragment((DocumentFragment) node);
        break;
    case Node.ELEMENT_NODE:
        visitElement((Element) node);
        break;
    case Node.TEXT_NODE:
        visitText((Text) node);
        break;
    case Node.CDATA_SECTION_NODE:
        visitCDATASection((CDATASection) node);
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        visitProcessingInstruction((ProcessingInstruction) node);
        break;
    case Node.ENTITY_REFERENCE_NODE:
        visitReference((EntityReference) node);
        break;
    case Node.COMMENT_NODE:
        visitComment((Comment) node);
        break;
    case Node.DOCUMENT_TYPE_NODE:
        break;
    case Node.ATTRIBUTE_NODE:
    case Node.ENTITY_NODE:
    default:
        throw new XMLStreamException("Unexpected DOM Node Type "
            + node.getNodeType()
        );
    }
}
 
Example 5
Source File: TreeWalkerImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/** Internal function.
 *  Return the first child Node, from the input node
 *  after applying filter, whatToshow.
 *  The current node is not consulted or set.
 */
Node getFirstChild(Node node) {
    if (node == null) return null;

    if ( !fEntityReferenceExpansion
         && node.getNodeType() == Node.ENTITY_REFERENCE_NODE)
        return null;
    Node newNode = node.getFirstChild();
    if (newNode == null)  return null;
    int accept = acceptNode(newNode);

    if (accept == NodeFilter.FILTER_ACCEPT)
        return newNode;
    else
    if (accept == NodeFilter.FILTER_SKIP
        && newNode.hasChildNodes())
    {
        Node fChild = getFirstChild(newNode);

        if (fChild == null) {
            return getNextSibling(newNode, node);
        }
        return fChild;
    }
    else
    //if (accept == NodeFilter.REJECT_NODE)
    {
        return getNextSibling(newNode, node);
    }


}
 
Example 6
Source File: TextImpl.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Concatenates the text of all logically-adjacent text nodes to the left of
 * the node
 * @param node
 * @param buffer
 * @param parent
 * @return true - if execution was stopped because the type of node
 *         other than EntityRef, Text, CDATA is encountered, otherwise
 *         return false
 */
private boolean getWholeTextBackward(Node node, StringBuffer buffer, Node parent){

    // boolean to indicate whether node is a child of an entity reference
    boolean inEntRef = false;
    if (parent!=null) {
            inEntRef = parent.getNodeType()==Node.ENTITY_REFERENCE_NODE;
    }

    while (node != null) {
        short type = node.getNodeType();
        if (type == Node.ENTITY_REFERENCE_NODE) {
            if (getWholeTextBackward(node.getLastChild(), buffer, node)){
                return true;
            }
        }
        else if (type == Node.TEXT_NODE ||
                 type == Node.CDATA_SECTION_NODE) {
            ((TextImpl)node).insertTextContent(buffer);
        }
        else {
            return true;
        }

        node = node.getPreviousSibling();
    }

    // if the parent node is an entity reference node, must
    // check nodes to the left of the parent entity reference node for logically adjacent
    // text nodes
    if (inEntRef) {
            getWholeTextBackward(parent.getPreviousSibling(), buffer, parent.getParentNode());
        return true;
    }

    return false;
}
 
Example 7
Source File: NodeIteratorImpl.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/** The method previousNode(Node) returns the previous node
 *  from the actual DOM tree.
 */
Node previousNode(Node node) {

    Node result;

    // if we're at the root, return null.
    if (node == fRoot) return null;

    // get sibling
    result = node.getPreviousSibling();
    if (result == null) {
        //if 1st sibling, return parent
        result = node.getParentNode();
        return result;
    }

    // if sibling has children, keep getting last child of child.
    if (result.hasChildNodes()
        && !(!fEntityReferenceExpansion
            && result != null
            && result.getNodeType() == Node.ENTITY_REFERENCE_NODE))

    {
        while (result.hasChildNodes()) {
            result = result.getLastChild();
        }
    }

    return result;
}
 
Example 8
Source File: DOM2SAX.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private String getNodeTypeFromCode(short code) {
    String retval = null;
    switch (code) {
    case Node.ATTRIBUTE_NODE :
        retval = "ATTRIBUTE_NODE"; break;
    case Node.CDATA_SECTION_NODE :
        retval = "CDATA_SECTION_NODE"; break;
    case Node.COMMENT_NODE :
        retval = "COMMENT_NODE"; break;
    case Node.DOCUMENT_FRAGMENT_NODE :
        retval = "DOCUMENT_FRAGMENT_NODE"; break;
    case Node.DOCUMENT_NODE :
        retval = "DOCUMENT_NODE"; break;
    case Node.DOCUMENT_TYPE_NODE :
        retval = "DOCUMENT_TYPE_NODE"; break;
    case Node.ELEMENT_NODE :
        retval = "ELEMENT_NODE"; break;
    case Node.ENTITY_NODE :
        retval = "ENTITY_NODE"; break;
    case Node.ENTITY_REFERENCE_NODE :
        retval = "ENTITY_REFERENCE_NODE"; break;
    case Node.NOTATION_NODE :
        retval = "NOTATION_NODE"; break;
    case Node.PROCESSING_INSTRUCTION_NODE :
        retval = "PROCESSING_INSTRUCTION_NODE"; break;
    case Node.TEXT_NODE:
        retval = "TEXT_NODE"; break;
    }
    return retval;
}
 
Example 9
Source File: TreeWalkerImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/** Internal function.
 *  Return the last child Node, from the input node
 *  after applying filter, whatToshow.
 *  The current node is not consulted or set.
 */
Node getLastChild(Node node) {

    if (node == null) return null;

    if ( !fEntityReferenceExpansion
         && node.getNodeType() == Node.ENTITY_REFERENCE_NODE)
        return null;

    Node newNode = node.getLastChild();
    if (newNode == null)  return null;

    int accept = acceptNode(newNode);

    if (accept == NodeFilter.FILTER_ACCEPT)
        return newNode;
    else
    if (accept == NodeFilter.FILTER_SKIP
        && newNode.hasChildNodes())
    {
        Node lChild = getLastChild(newNode);
        if (lChild == null) {
            return getPreviousSibling(newNode, node);
        }
        return lChild;
    }
    else
    //if (accept == NodeFilter.REJECT_NODE)
    {
        return getPreviousSibling(newNode, node);
    }


}
 
Example 10
Source File: DocumentImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * NON-DOM INTERNAL: Pre-mutation context check, in
 * preparation for later generating DOMAttrModified events.
 * Determines whether this node is within an Attr
 * @param node node to get enclosing attribute for
 * @return either a description of that Attr, or null if none such.
 */
protected void saveEnclosingAttr(NodeImpl node) {
    savedEnclosingAttr = null;
    // MUTATION PREPROCESSING AND PRE-EVENTS:
    // If we're within the scope of an Attr and DOMAttrModified
    // was requested, we need to preserve its previous value for
    // that event.
    LCount lc = LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
    if (lc.total > 0) {
        NodeImpl eventAncestor = node;
        while (true) {
            if (eventAncestor == null)
                return;
            int type = eventAncestor.getNodeType();
            if (type == Node.ATTRIBUTE_NODE) {
                EnclosingAttr retval = new EnclosingAttr();
                retval.node = (AttrImpl) eventAncestor;
                retval.oldvalue = retval.node.getNodeValue();
                savedEnclosingAttr = retval;
                return;
            }
            else if (type == Node.ENTITY_REFERENCE_NODE)
                eventAncestor = eventAncestor.parentNode();
            else if (type == Node.TEXT_NODE)
                eventAncestor = eventAncestor.parentNode();
            else
                return;
            // Any other parent means we're not in an Attr
        }
    }
}
 
Example 11
Source File: PrefixResolverDefault.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Given a namespace, get the corrisponding prefix.
 * Warning: This will not work correctly if namespaceContext
 * is an attribute node.
 * @param prefix Prefix to resolve.
 * @param namespaceContext Node from which to start searching for a
 * xmlns attribute that binds a prefix to a namespace.
 * @return Namespace that prefix resolves to, or null if prefix
 * is not bound.
 */
public String getNamespaceForPrefix(String prefix,
                                    org.w3c.dom.Node namespaceContext)
{

  Node parent = namespaceContext;
  String namespace = null;

  if (prefix.equals("xml"))
  {
    namespace = Constants.S_XMLNAMESPACEURI;
  }
  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 12
Source File: EntityReferenceImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
     * NON-DOM: compute string representation of the entity reference.
 * This method is used to retrieve a string value for an attribute node that has child nodes.
     * @return String representing a value of this entity ref. or
 *          null if any node other than EntityReference, Text is encountered
 *          during computation
     */
protected String getEntityRefValue (){
    if (needsSyncChildren()){
        synchronizeChildren();
    }

    String value = "";
    if (firstChild != null){
      if (firstChild.getNodeType() == Node.ENTITY_REFERENCE_NODE){
          value = ((EntityReferenceImpl)firstChild).getEntityRefValue();
      }
      else if (firstChild.getNodeType() == Node.TEXT_NODE){
        value = firstChild.getNodeValue();
      }
      else {
         // invalid to have other types of nodes in attr value
        return null;
      }

      if (firstChild.nextSibling == null){
        return value;
      }
      else {
        StringBuffer buff = new StringBuffer(value);
        ChildNode next = firstChild.nextSibling;
        while (next != null){

            if (next.getNodeType() == Node.ENTITY_REFERENCE_NODE){
               value = ((EntityReferenceImpl)next).getEntityRefValue();
            }
            else if (next.getNodeType() == Node.TEXT_NODE){
              value = next.getNodeValue();
            }
            else {
                // invalid to have other types of nodes in attr value
                return null;
            }
            buff.append(value);
            next = next.nextSibling;

        }
        return buff.toString();
      }
    }
    return "";
}
 
Example 13
Source File: StaxUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static void writeNode(Node n, XMLStreamWriter writer, boolean repairing)
    throws XMLStreamException {

    switch (n.getNodeType()) {
    case Node.ELEMENT_NODE:
        writeElement((Element)n, writer, repairing);
        break;
    case Node.TEXT_NODE:
        writer.writeCharacters(((Text)n).getNodeValue());
        break;
    case Node.COMMENT_NODE:
        writer.writeComment(((Comment)n).getData());
        break;
    case Node.CDATA_SECTION_NODE:
        writer.writeCData(((CDATASection)n).getData());
        break;
    case Node.ENTITY_REFERENCE_NODE:
        writer.writeEntityRef(((EntityReference)n).getNodeValue());
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        ProcessingInstruction pi = (ProcessingInstruction)n;
        writer.writeProcessingInstruction(pi.getTarget(), pi.getData());
        break;
    case Node.DOCUMENT_NODE:
        writeDocument((Document)n, writer, repairing);
        break;
    case Node.DOCUMENT_FRAGMENT_NODE: {
        DocumentFragment frag = (DocumentFragment)n;
        Node child = frag.getFirstChild();
        while (child != null) {
            writeNode(child, writer, repairing);
            child = child.getNextSibling();
        }
        break;
    }
    case Node.DOCUMENT_TYPE_NODE:
        try {
            if (((DocumentType)n).getTextContent() != null) {
                writer.writeDTD(((DocumentType)n).getTextContent());
            }
        } catch (UnsupportedOperationException ex) {
            //can we ignore?  DOM writers really don't allow this
            //as there isn't a way to write a DTD in dom
        }
        break;
    default:
        throw new IllegalStateException("Found type: " + n.getClass().getName());
    }
}
 
Example 14
Source File: PrefixResolverDefault.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Given a namespace, get the corrisponding prefix.
 * Warning: This will not work correctly if namespaceContext
 * is an attribute node.
 * @param prefix Prefix to resolve.
 * @param namespaceContext Node from which to start searching for a
 * xmlns attribute that binds a prefix to a namespace.
 * @return Namespace that prefix resolves to, or null if prefix
 * is not bound.
 */
public String getNamespaceForPrefix(String prefix,
                                    org.w3c.dom.Node namespaceContext)
{

  Node parent = namespaceContext;
  String namespace = null;

  if (prefix.equals("xml"))
  {
    namespace = Constants.S_XMLNAMESPACEURI;
  }
  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 15
Source File: DOMUtil.java    From hottub 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: XMLUtils.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
@SuppressWarnings("fallthrough")
private static void circumventBug2650internal(Node node) {
    Node parent = null;
    Node sibling = null;
    final String namespaceNs = Constants.NamespaceSpecNS;
    do {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE :
            Element element = (Element) node;
            if (!element.hasChildNodes()) {
                break;
            }
            if (element.hasAttributes()) {
                NamedNodeMap attributes = element.getAttributes();
                int attributesLength = attributes.getLength();

                for (Node child = element.getFirstChild(); child!=null;
                    child = child.getNextSibling()) {

                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    Element childElement = (Element) child;

                    for (int i = 0; i < attributesLength; i++) {
                        Attr currentAttr = (Attr) attributes.item(i);
                        if (!namespaceNs.equals(currentAttr.getNamespaceURI())) {
                            continue;
                        }
                        if (childElement.hasAttributeNS(namespaceNs,
                                                        currentAttr.getLocalName())) {
                            continue;
                        }
                        childElement.setAttributeNS(namespaceNs,
                                                    currentAttr.getName(),
                                                    currentAttr.getNodeValue());
                    }
                }
            }
        case Node.ENTITY_REFERENCE_NODE :
        case Node.DOCUMENT_NODE :
            parent = node;
            sibling = node.getFirstChild();
            break;
        }
        while ((sibling == null) && (parent != null)) {
            sibling = parent.getNextSibling();
            parent = parent.getParentNode();
        }
        if (sibling == null) {
            return;
        }

        node = sibling;
        sibling = node.getNextSibling();
    } while (true);
}
 
Example 17
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;
    final String prefixColon = prefix + ':';

    if (prefix.equals("xml")) {
        namespace = XMLConstants.XML_NS_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().startsWith(prefixColon))
                    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();
        }
    }

    if(prefix.equals(""))
        return "";  // default namespace
    return namespace;
}
 
Example 18
Source File: JAXBDataBinding.java    From cxf with Apache License 2.0 4 votes vote down vote up
public Node cloneNode(Document document, Node node, boolean deep) throws DOMException {
    if (document == null || node == null) {
        return null;
    }
    int type = node.getNodeType();

    if (node.getOwnerDocument() == document) {
        return node.cloneNode(deep);
    }
    Node clone;
    switch (type) {
    case Node.CDATA_SECTION_NODE:
        clone = document.createCDATASection(node.getNodeValue());
        break;
    case Node.COMMENT_NODE:
        clone = document.createComment(node.getNodeValue());
        break;
    case Node.ENTITY_REFERENCE_NODE:
        clone = document.createEntityReference(node.getNodeName());
        break;
    case Node.ELEMENT_NODE:
        clone = document.createElement(node.getNodeName());
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            ((Element)clone).setAttributeNS(attributes.item(i).getNamespaceURI(),
                                            attributes.item(i).getNodeName(),
                                            attributes.item(i).getNodeValue());
        }
        try {
            clone.setUserData("location", node.getUserData("location"), null);
        } catch (Throwable t) {
            //non DOM level 3
        }
        break;

    case Node.TEXT_NODE:
        clone = document.createTextNode(node.getNodeValue());
        break;
    default:
        return null;
    }
    if (deep && type == Node.ELEMENT_NODE) {
        Node child = node.getFirstChild();
        while (child != null) {
            clone.appendChild(cloneNode(document, child, true));
            child = child.getNextSibling();
        }
    }
    return clone;
}
 
Example 19
Source File: PrefixResolverDefault.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * Given a namespace, get the corrisponding prefix.
 * Warning: This will not work correctly if namespaceContext
 * is an attribute node.
 * @param prefix Prefix to resolve.
 * @param namespaceContext Node from which to start searching for a
 * xmlns attribute that binds a prefix to a namespace.
 * @return Namespace that prefix resolves to, or null if prefix
 * is not bound.
 */
public String getNamespaceForPrefix(String prefix,
                                    org.w3c.dom.Node namespaceContext)
{

  Node parent = namespaceContext;
  String namespace = null;

  if (prefix.equals("xml"))
  {
    namespace = Constants.S_XMLNAMESPACEURI;
  }
  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 20
Source File: EntityReferenceImpl.java    From openjdk-8-source with GNU General Public License v2.0 2 votes vote down vote up
/**
 * A short integer indicating what type of node this is. The named
 * constants for this value are defined in the org.w3c.dom.Node interface.
 */
public short getNodeType() {
    return Node.ENTITY_REFERENCE_NODE;
}