Java Code Examples for org.w3c.dom.Node.insertBefore()

The following are Jave code examples for showing how to use insertBefore() of the org.w3c.dom.Node class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: Schema2BeansUtil.java   View Source Code Vote up 7 votes
/**
 * Merge child nodes
 * 
 * @param node     current node base
 * @param childNode child node if exist
 * @param foundBean child bean
 * @param currentChild current child node
 * @param patternChild current pattern child
 * @param nodeMap node map
 * @param document document
 * @param patternBean pattern bean
 * @param children list relevant childs current node base
 */
private static void mergeChildNodes(Node node, Node childNode, BaseBean foundBean,
        Node currentChild, Node patternChild, Map nodeMap, Document document,
        BaseBean patternBean, List children) {
    Node foundChild = childNode;
    if (foundChild == null) {
        foundChild = takeEqualNode(children, patternChild);
    }
    if (foundChild != null) {
        if (foundChild != currentChild) {
            node.removeChild(foundChild);
            node.insertBefore(foundChild, currentChild);
        }
        if (foundBean != null) {
            mergeBeans(nodeMap, foundBean, patternBean);
        } else if (isRelevantNode(foundChild) && foundChild.hasChildNodes()) {
            mergeNode(nodeMap, foundChild, patternChild);
        } else {
            foundChild.setNodeValue(patternChild.getNodeValue());
        }
    } else {
        Node child = document.importNode(patternChild, true);
        node.insertBefore(child, currentChild);
    }
}
 
Example 2
Project: jdk8u-jdk   File: DOMKeyInfo.java   View Source Code Vote up 6 votes
private void marshal(Node parent, Element kiElem, Node nextSibling,
                     String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    // create and append KeyInfoType elements
    for (XMLStructure kiType : keyInfoTypes) {
        if (kiType instanceof DOMStructure) {
            ((DOMStructure)kiType).marshal(kiElem, dsPrefix, context);
        } else {
            DOMUtils.appendChild(kiElem,
                ((javax.xml.crypto.dom.DOMStructure)kiType).getNode());
        }
    }

    // append id attribute
    DOMUtils.setAttributeID(kiElem, "Id", id);

    parent.insertBefore(kiElem, nextSibling);
}
 
Example 3
Project: openjdk-jdk10   File: DOMKeyInfo.java   View Source Code Vote up 6 votes
private void marshal(Node parent, Element kiElem, Node nextSibling,
                     String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    // create and append KeyInfoType elements
    for (XMLStructure kiType : keyInfoTypes) {
        if (kiType instanceof DOMStructure) {
            ((DOMStructure)kiType).marshal(kiElem, dsPrefix, context);
        } else {
            DOMUtils.appendChild(kiElem,
                ((javax.xml.crypto.dom.DOMStructure)kiType).getNode());
        }
    }

    // append id attribute
    DOMUtils.setAttributeID(kiElem, "Id", id);

    parent.insertBefore(kiElem, nextSibling);
}
 
Example 4
Project: openjdk-jdk10   File: TextImpl.java   View Source Code Vote up 5 votes
/**
 * Break a text node into two sibling nodes. (Note that if the current node
 * has no parent, they won't wind up as "siblings" -- they'll both be
 * orphans.)
 *
 * @param offset
 *            The offset at which to split. If offset is at the end of the
 *            available data, the second node will be empty.
 *
 * @return A reference to the new node (containing data after the offset
 *         point). The original node will contain data up to that point.
 *
 * @throws DOMException(INDEX_SIZE_ERR)
 *             if offset is <0 or >length.
 *
 * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR)
 *             if node is read-only.
 */
public Text splitText(int offset)
    throws DOMException {

    if (isReadOnly()) {
        throw new DOMException(
        DOMException.NO_MODIFICATION_ALLOWED_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null));
    }

    if (needsSyncData()) {
        synchronizeData();
    }
    if (offset < 0 || offset > data.length() ) {
        throw new DOMException(DOMException.INDEX_SIZE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null));
    }

    // split text into two separate nodes
    Text newText =
        getOwnerDocument().createTextNode(data.substring(offset));
    setNodeValue(data.substring(0, offset));

    // insert new text node
    Node parentNode = getParentNode();
    if (parentNode != null) {
        parentNode.insertBefore(newText, nextSibling);
    }

    return newText;

}
 
Example 5
Project: jdk8u-jdk   File: DOMXMLSignature.java   View Source Code Vote up 5 votes
public void marshal(Node parent, Node nextSibling, String dsPrefix,
                    DOMCryptoContext context)
    throws MarshalException
{
    ownerDoc = DOMUtils.getOwnerDocument(parent);
    sigElem = DOMUtils.createElement(ownerDoc, "Signature",
                                     XMLSignature.XMLNS, dsPrefix);

    // append xmlns attribute
    if (dsPrefix == null || dsPrefix.length() == 0) {
        sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
                               XMLSignature.XMLNS);
    } else {
        sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" +
                               dsPrefix, XMLSignature.XMLNS);
    }

    // create and append SignedInfo element
    ((DOMSignedInfo)si).marshal(sigElem, dsPrefix, context);

    // create and append SignatureValue element
    ((DOMSignatureValue)sv).marshal(sigElem, dsPrefix, context);

    // create and append KeyInfo element if necessary
    if (ki != null) {
        ((DOMKeyInfo)ki).marshal(sigElem, null, dsPrefix, context);
    }

    // create and append Object elements if necessary
    for (int i = 0, size = objects.size(); i < size; i++) {
        ((DOMXMLObject)objects.get(i)).marshal(sigElem, dsPrefix, context);
    }

    // append Id attribute
    DOMUtils.setAttributeID(sigElem, "Id", id);

    parent.insertBefore(sigElem, nextSibling);
}
 
Example 6
Project: OpenJSharp   File: DOMXMLSignature.java   View Source Code Vote up 5 votes
public void marshal(Node parent, Node nextSibling, String dsPrefix,
                    DOMCryptoContext context)
    throws MarshalException
{
    ownerDoc = DOMUtils.getOwnerDocument(parent);
    sigElem = DOMUtils.createElement(ownerDoc, "Signature",
                                     XMLSignature.XMLNS, dsPrefix);

    // append xmlns attribute
    if (dsPrefix == null || dsPrefix.length() == 0) {
        sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
                               XMLSignature.XMLNS);
    } else {
        sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" +
                               dsPrefix, XMLSignature.XMLNS);
    }

    // create and append SignedInfo element
    ((DOMSignedInfo)si).marshal(sigElem, dsPrefix, context);

    // create and append SignatureValue element
    ((DOMSignatureValue)sv).marshal(sigElem, dsPrefix, context);

    // create and append KeyInfo element if necessary
    if (ki != null) {
        ((DOMKeyInfo)ki).marshal(sigElem, null, dsPrefix, context);
    }

    // create and append Object elements if necessary
    for (int i = 0, size = objects.size(); i < size; i++) {
        ((DOMXMLObject)objects.get(i)).marshal(sigElem, dsPrefix, context);
    }

    // append Id attribute
    DOMUtils.setAttributeID(sigElem, "Id", id);

    parent.insertBefore(sigElem, nextSibling);
}
 
Example 7
Project: OpenJSharp   File: SAX2DOM.java   View Source Code Vote up 5 votes
private void appendTextNode() {
    if (_textBuffer.length() > 0) {
        final Node last = (Node)_nodeStk.peek();
        if (last == _root && _nextSiblingCache != null) {
            _lastSibling = last.insertBefore(_document.createTextNode(_textBuffer.toString()), _nextSiblingCache);
        }
        else {
            _lastSibling = last.appendChild(_document.createTextNode(_textBuffer.toString()));
        }
        _textBuffer.setLength(0);
    }
}
 
Example 8
Project: OpenJSharp   File: SAX2DOM.java   View Source Code Vote up 5 votes
/**
 * adds processing instruction node to DOM.
 */
public void processingInstruction(String target, String data) {
    appendTextNode();
    final Node last = (Node)_nodeStk.peek();
    ProcessingInstruction pi = _document.createProcessingInstruction(
            target, data);
    if (pi != null){
      if (last == _root && _nextSibling != null)
          last.insertBefore(pi, _nextSibling);
      else
          last.appendChild(pi);

      _lastSibling = pi;
    }
}
 
Example 9
Project: OpenJSharp   File: DOMNormalizer.java   View Source Code Vote up 5 votes
protected final void expandEntityRef (Node parent, Node reference){
    Node kid, next;
    for (kid = reference.getFirstChild(); kid != null; kid = next) {
        next = kid.getNextSibling();
        parent.insertBefore(kid, reference);
    }
}
 
Example 10
Project: OpenJSharp   File: TextImpl.java   View Source Code Vote up 5 votes
/**
 * Break a text node into two sibling nodes. (Note that if the current node
 * has no parent, they won't wind up as "siblings" -- they'll both be
 * orphans.)
 *
 * @param offset
 *            The offset at which to split. If offset is at the end of the
 *            available data, the second node will be empty.
 *
 * @return A reference to the new node (containing data after the offset
 *         point). The original node will contain data up to that point.
 *
 * @throws DOMException(INDEX_SIZE_ERR)
 *             if offset is <0 or >length.
 *
 * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR)
 *             if node is read-only.
 */
public Text splitText(int offset)
    throws DOMException {

    if (isReadOnly()) {
        throw new DOMException(
        DOMException.NO_MODIFICATION_ALLOWED_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null));
    }

    if (needsSyncData()) {
        synchronizeData();
    }
    if (offset < 0 || offset > data.length() ) {
        throw new DOMException(DOMException.INDEX_SIZE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null));
    }

    // split text into two separate nodes
    Text newText =
        getOwnerDocument().createTextNode(data.substring(offset));
    setNodeValue(data.substring(0, offset));

    // insert new text node
    Node parentNode = getParentNode();
    if (parentNode != null) {
        parentNode.insertBefore(newText, nextSibling);
    }

    return newText;

}
 
Example 11
Project: openjdk-jdk10   File: SAX2DOM.java   View Source Code Vote up 5 votes
/**
 * adds processing instruction node to DOM.
 */
public void processingInstruction(String target, String data) {
    appendTextNode();
    final Node last = (Node)_nodeStk.peek();
    ProcessingInstruction pi = _document.createProcessingInstruction(
            target, data);
    if (pi != null){
      if (last == _root && _nextSibling != null)
          last.insertBefore(pi, _nextSibling);
      else
          last.appendChild(pi);

      _lastSibling = pi;
    }
}
 
Example 12
Project: Hydrograph   File: ParseExternalElements.java   View Source Code Vote up 5 votes
private void insertOperationNodesBeforeOutSocket(Document xmlDocument, Node parent, List<Node> nodes) {
	Node copiedNode;
	Node outSocket = getOutSocket(parent);
	for (int i = 0; i < nodes.size(); i++) {
		copiedNode = xmlDocument.importNode(nodes.get(i), true);
		parent.insertBefore(copiedNode, outSocket);
	}
}
 
Example 13
Project: openjdk-jdk10   File: DOMBuilder.java   View Source Code Vote up 4 votes
/**
 * Append a node to the current container.
 *
 * @param newNode New node to append
 */
protected void append(Node newNode) throws org.xml.sax.SAXException
{

  Node currentNode = m_currentNode;

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

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

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

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

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

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

    if (ok)
    {
      if (m_nextSibling != null)
        m_doc.insertBefore(newNode, m_nextSibling);
      else
        m_doc.appendChild(newNode);
    }
  }
}
 
Example 14
Project: myfaces-trinidad   File: AddChildDocumentChange.java   View Source Code Vote up 4 votes
/**
 * Given the DOM Node representing a Component, apply any necessary
 * DOM changes.
 */
public void changeDocument(Node componentNode)
{
  if (componentNode == null)
    throw new IllegalArgumentException(_LOG.getMessage(
      "NO_NODE_SPECIFIED"));
  
  // get the fragement, imported into the target document
  DocumentFragment targetFragment = 
    getImportedComponentFragment(componentNode);
  
  // assume that we'll be appending
  Node insertBeforeNode = null;
  
  // search children for the _insertBefore id
  if (_insertBeforeId != null)
  {
    String insertBeforeID = _insertBeforeId;
    
    Node currChild = componentNode.getFirstChild();
    Node idAttr;
    
    while (currChild != null)
    {
      NamedNodeMap attributes = currChild.getAttributes();
      
      if (attributes != null)
      {
        idAttr = attributes.getNamedItem("id");
        if (idAttr != null && insertBeforeID.equals(idAttr.getNodeValue()))
        {
          insertBeforeNode = currChild;
          break;
        }
      }
      currChild = currChild.getNextSibling();
    }
  }    
  
  // insert our DocumentFragment in the correct position
  componentNode.insertBefore(targetFragment, insertBeforeNode);
}
 
Example 15
Project: myfaces-trinidad   File: MoveChildComponentChange.java   View Source Code Vote up 4 votes
/**
 * Given the DOM Node representing a Component, apply any necessary
 * DOM changes. The node passed will be the Node that is a common parent for
 * the movable child and the destination container.
 * There is a limitation with the document change, that the movable child 
 * Node, destination container Node, and the common parent Node have to belong
 * to the same document.
 * @param changeTargetNode DOM Node that is a common parent for the movable
 * child and the destination container.
 * @throws IllegalArgumentException If changeTargeNode were to be null.
 */
public void changeDocument(Node changeTargetNode)
{
  if (changeTargetNode == null)
    throw new IllegalArgumentException(_LOG.getMessage("NO_NODE_SPECIFIED"));

  if ( !_moveCompDocPath.equals(_destinationContainerDocPath) ||
       !_moveCompDocPath.equals(_commonParentDocPath) )
  {
    // If all three participants are not in same doc, we cannot proceed with appling doc change.
    // Throw an exception so that ChangeManagers can handle this failure and do alternate
    //  processing (eg. add a component change given that doc change failed)
    throw new IllegalStateException(
      _LOG.getMessage("MOVE_PARTICIPANTS_NOT_IN_SAME_DOC", 
                      new Object[] {_moveCompDocPath,
                                    _destinationContainerDocPath,
                                    _commonParentDocPath}));
  }

  // Move involves four steps.
  // 1. Finding the child node, the source of move
  Node movableChildNode = 
    ChangeUtils.__findNodeByScopedId(changeTargetNode, 
                                     _moveCompScopedIdAtSource, 
                                     Integer.MAX_VALUE);
  
  if(movableChildNode == null)
  {
    _LOG.warning("MOVABLE_CHILD_NOT_FOUND", _moveCompScopedIdAtSource);
    return;
  }
  
  // 2. Finding the destination container node
  Node destinationContainerNode = 
    ChangeUtils.__findNodeByScopedId(changeTargetNode, 
                                     _destinationContainerScopedId, 
                                     Integer.MAX_VALUE);

  
  if(destinationContainerNode == null)
  {
    _LOG.warning("DESTINATION_CONTAINER_NOT_FOUND", _destinationContainerScopedId);
    return;
  }
  
  //3. Finding the neighbor at the destination
  Node insertBeforeNode = (_insertBeforeCompId == null) ? 
    null:ChangeUtils.__findNodeByScopedId(destinationContainerNode, 
                                          _insertBeforeCompId, 
                                          1);
  // insertBeforeId was specified, but corresponding component is missing.
  //  Abort the move.
  if(_insertBeforeCompId != null && insertBeforeNode == null)
  {
    _LOG.warning("INSERT_BEFORE_NOT_FOUND", _insertBeforeCompId);
    return;
  }

  //4. Atomically move the child.
  destinationContainerNode.insertBefore(movableChildNode, insertBeforeNode);
}
 
Example 16
Project: ChronoBike   File: XmlHelper.java   View Source Code Vote up 4 votes
static public void SortChilds(Node parent, String childname) {
		Node a;                            // Pour parcourrir les elements de parent.
		Node b;                            // Pour parcourrir les elements de parent.
		Node min;                          // Pointe sur le node "minimum" (alphabetiquement).
		String btext;                            // La valeur de l'element b.
		String mintext;                          // La valeur de l'element min
		boolean replace;

//********************* Parcourre tous les elements de type childname ****************
		a=SelectSingleNode(parent,childname);
		if (a!=null) {
			do {
//..................... Pour chaque element ..........................................
				min=a;
				mintext=GetNodeText(min);

//.................. On cherche un element plus petit ................................
				b=SelectSingleNode(a,"following-sibling::"+childname+"[position()=1]");
				replace=false;

				if (b!=null) {
					do {
						btext = GetNodeText(b);
						if (btext.compareTo(mintext)<0) {
							min=b;
							mintext=GetNodeText(min);
							replace=true;
						}
						b=SelectSingleNode(b,"following-sibling::"+childname+"[position()=1]");
					} while (b!=null);
				}
        
//............. Si on a trouve un element plus petit, on remplace ....................
				if (replace) {
					parent.removeChild(min);
					parent.insertBefore(min,a);
					a = min;
				}
				a=SelectSingleNode(a,"following-sibling::"+childname+"[position()=1]");
			} while (a!=null);
		}
	}
 
Example 17
Project: OpenJSharp   File: SAX2DOM.java   View Source Code Vote up 4 votes
public void startElement(String namespace, String localName, String qName,
        Attributes attrs)
    {
        appendTextNode();
        if (needToSetDocumentInfo) {
            setDocumentInfo();
            needToSetDocumentInfo = false;
        }

        final Element tmp = (Element)_document.createElementNS(namespace, qName);

        // Add namespace declarations first
        if (_namespaceDecls != null) {
            final int nDecls = _namespaceDecls.size();
            for (int i = 0; i < nDecls; i++) {
                final String prefix = (String) _namespaceDecls.elementAt(i++);

                if (prefix == null || prefix.equals(EMPTYSTRING)) {
                    tmp.setAttributeNS(XMLNS_URI, XMLNS_PREFIX,
                        (String) _namespaceDecls.elementAt(i));
                }
                else {
                    tmp.setAttributeNS(XMLNS_URI, XMLNS_STRING + prefix,
                        (String) _namespaceDecls.elementAt(i));
                }
            }
            _namespaceDecls.clear();
        }

        // Add attributes to element
/*      final int nattrs = attrs.getLength();
        for (int i = 0; i < nattrs; i++) {
            if (attrs.getLocalName(i) == null) {
                tmp.setAttribute(attrs.getQName(i), attrs.getValue(i));
            }
            else {
                tmp.setAttributeNS(attrs.getURI(i), attrs.getQName(i),
                    attrs.getValue(i));
            }
        } */


        // Add attributes to element
        final int nattrs = attrs.getLength();
        for (int i = 0; i < nattrs; i++) {
            // checking if Namespace processing is being done
            String attQName = attrs.getQName(i);
            String attURI = attrs.getURI(i);
            if (attrs.getLocalName(i).equals("")) {
                tmp.setAttribute(attQName, attrs.getValue(i));
                if (attrs.getType(i).equals("ID")) {
                    tmp.setIdAttribute(attQName, true);
                }
            } else {
                tmp.setAttributeNS(attURI, attQName, attrs.getValue(i));
                if (attrs.getType(i).equals("ID")) {
                    tmp.setIdAttributeNS(attURI, attrs.getLocalName(i), true);
                }
            }
        }


        // Append this new node onto current stack node
        Node last = (Node)_nodeStk.peek();

        // If the SAX2DOM is created with a non-null next sibling node,
        // insert the result nodes before the next sibling under the root.
        if (last == _root && _nextSibling != null)
            last.insertBefore(tmp, _nextSibling);
        else
            last.appendChild(tmp);

        // Push this node onto stack
        _nodeStk.push(tmp);
        _lastSibling = null;
    }
 
Example 18
Project: openjdk-jdk10   File: SAX2DOM.java   View Source Code Vote up 4 votes
public void startElement(String namespace, String localName, String qName,
        Attributes attrs)
    {
        appendTextNode();
        if (needToSetDocumentInfo) {
            setDocumentInfo();
            needToSetDocumentInfo = false;
        }

        final Element tmp = (Element)_document.createElementNS(namespace, qName);

        // Add namespace declarations first
        if (_namespaceDecls != null) {
            final int nDecls = _namespaceDecls.size();
            for (int i = 0; i < nDecls; i++) {
                final String prefix = (String) _namespaceDecls.elementAt(i++);

                if (prefix == null || prefix.equals(EMPTYSTRING)) {
                    tmp.setAttributeNS(XMLNS_URI, XMLNS_PREFIX,
                        (String) _namespaceDecls.elementAt(i));
                }
                else {
                    tmp.setAttributeNS(XMLNS_URI, XMLNS_STRING + prefix,
                        (String) _namespaceDecls.elementAt(i));
                }
            }
            _namespaceDecls.clear();
        }

        // Add attributes to element
/*      final int nattrs = attrs.getLength();
        for (int i = 0; i < nattrs; i++) {
            if (attrs.getLocalName(i) == null) {
                tmp.setAttribute(attrs.getQName(i), attrs.getValue(i));
            }
            else {
                tmp.setAttributeNS(attrs.getURI(i), attrs.getQName(i),
                    attrs.getValue(i));
            }
        } */


        // Add attributes to element
        final int nattrs = attrs.getLength();
        for (int i = 0; i < nattrs; i++) {
            // checking if Namespace processing is being done
            String attQName = attrs.getQName(i);
            String attURI = attrs.getURI(i);
            if (attrs.getLocalName(i).equals("")) {
                tmp.setAttribute(attQName, attrs.getValue(i));
                if (attrs.getType(i).equals("ID")) {
                    tmp.setIdAttribute(attQName, true);
                }
            } else {
                tmp.setAttributeNS(attURI, attQName, attrs.getValue(i));
                if (attrs.getType(i).equals("ID")) {
                    tmp.setIdAttributeNS(attURI, attrs.getLocalName(i), true);
                }
            }
        }


        // Append this new node onto current stack node
        Node last = (Node)_nodeStk.peek();

        // If the SAX2DOM is created with a non-null next sibling node,
        // insert the result nodes before the next sibling under the root.
        if (last == _root && _nextSibling != null)
            last.insertBefore(tmp, _nextSibling);
        else
            last.appendChild(tmp);

        // Push this node onto stack
        _nodeStk.push(tmp);
        _lastSibling = null;
    }
 
Example 19
Project: OpenJSharp   File: DOMBuilder.java   View Source Code Vote up 4 votes
/**
 * Append a node to the current container.
 *
 * @param newNode New node to append
 */
protected void append(Node newNode) throws org.xml.sax.SAXException
{

  Node currentNode = m_currentNode;

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

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

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

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

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

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

    if (ok)
    {
      if (m_nextSibling != null)
        m_doc.insertBefore(newNode, m_nextSibling);
      else
        m_doc.appendChild(newNode);
    }
  }
}
 
Example 20
Project: monarch   File: XmlUtils.java   View Source Code Vote up 4 votes
/*****
 * Adds a new node or replaces an existing node in the Document
 * 
 * @param doc Target document where the node will added
 * @param xmlEntity contains definition of the xml entity
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static void addNewNode(final Document doc, final XmlEntity xmlEntity)
    throws IOException, XPathExpressionException, SAXException, ParserConfigurationException {
  // Build up map per call to avoid issues with caching wrong version of the map.
  final LinkedHashMap<String, CacheElement> elementOrderMap = CacheElement.buildElementMap(doc);

  final Node newNode = createNode(doc, xmlEntity.getXmlDefinition());
  final Node root = doc.getDocumentElement();
  final int incomingElementOrder =
      getElementOrder(elementOrderMap, xmlEntity.getNamespace(), xmlEntity.getType());

  boolean nodeAdded = false;
  NodeList nodes = root.getChildNodes();
  final int length = nodes.getLength();
  for (int i = 0; i < length; i++) {
    final Node node = nodes.item(i);

    if (node instanceof Element) {
      final Element childElement = (Element) node;
      final String type = childElement.getLocalName();
      final String namespace = childElement.getNamespaceURI();

      if (namespace.equals(xmlEntity.getNamespace()) && type.equals(xmlEntity.getType())) {
        // TODO this should really be checking all attributes in xmlEntity.getAttributes
        // First check if the element has a name
        String nameOrId = getAttribute(childElement, "name");
        // If not then check if the element has an Id
        if (nameOrId == null) {
          nameOrId = getAttribute(childElement, "id");
        }

        if (nameOrId != null) {
          // If there is a match , then replace the existing node with the incoming node
          if (nameOrId.equals(xmlEntity.getNameOrId())) {
            root.replaceChild(newNode, node);
            nodeAdded = true;
            break;
          }
        } else {
          // This element does not have any name or id identifier for e.g PDX and gateway-receiver
          // If there is only one element of that type then replace it with the incoming node
          if (!isMultiple(elementOrderMap, namespace, type)) {
            root.replaceChild(newNode, node);
            nodeAdded = true;
            break;
          }
        }
      } else {
        if (incomingElementOrder < getElementOrder(elementOrderMap, namespace, type)) {
          root.insertBefore(newNode, node);
          nodeAdded = true;
          break;
        }
      }
    }
  }
  if (!nodeAdded) {
    root.appendChild(newNode);
  }
}