org.w3c.dom.Element#replaceChild ( )源码实例Demo

下面列出了org.w3c.dom.Element#replaceChild ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: OpenEstate-IO   文件: XmlUtils.java
/**
 * Replace all text values of a {@link Node} with CDATA values.
 *
 * @param doc  the document to update
 * @param node the node to update
 */
public static void replaceTextWithCData(Document doc, Node node) {
    if (node instanceof Text) {
        Text text = (Text) node;
        CDATASection cdata = doc.createCDATASection(text.getTextContent());
        Element parent = (Element) text.getParentNode();
        parent.replaceChild(cdata, text);
    } else if (node instanceof Element) {
        //LOGGER.debug( "ELEMENT " + element.getTagName() );
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            //LOGGER.debug( "> " + children.item( i ).getClass().getName() );
            XmlUtils.replaceTextWithCData(doc, children.item(i));
        }
    }
}
 
源代码2 项目: caja   文件: TestSummary.java
private static int rewriteChildElements(
    Element parent, String oldName, String newName) {
  int nRewritten = 0;
  for (Node c = parent.getFirstChild(); c != null; c = c.getNextSibling()) {
    if (c instanceof Element && oldName.equals(c.getNodeName())) {
      Element el = (Element) c;
      Element replacement = parent.getOwnerDocument().createElement(newName);
      while (el.getFirstChild() != null) {
        replacement.appendChild(el.getFirstChild());
      }
      NamedNodeMap attrMap = el.getAttributes();
      Attr[] attrs = new Attr[attrMap.getLength()];
      for (int i = 0, n = attrMap.getLength(); i < n; ++i) {
        attrs[i] = (Attr) attrMap.item(i);
      }
      for (Attr attr : attrs) {
        el.removeAttributeNode(attr);
        replacement.setAttributeNode(attr);
      }
      parent.replaceChild(replacement, el);
      ++nRewritten;
    }
  }
  return nRewritten;
}
 
源代码3 项目: rice   文件: EDLControllerFactory.java
public static EDLController createEDLController(EDocLiteAssociation edlAssociation, EDLGlobalConfig edlGlobalConfig, DocumentRouteHeaderValue document) {
	EDLController edlController = createEDLController(edlAssociation, edlGlobalConfig);
	try {
		Document defaultDom = edlController.getDefaultDOM();
		Document documentDom = XmlHelper.readXml(document.getDocContent());
		// get the data node and import it into our default DOM
		Element documentData = (Element) documentDom.getElementsByTagName(EDLXmlUtils.DATA_E).item(0);
		if (documentData != null) {
			Element defaultDomEDL = EDLXmlUtils.getEDLContent(defaultDom, false);
			Element defaultDomData = (Element) defaultDomEDL.getElementsByTagName(EDLXmlUtils.DATA_E).item(0);
			defaultDomEDL.replaceChild(defaultDom.importNode(documentData, true), defaultDomData);
		}
		if (LOG.isDebugEnabled()) {
			LOG.debug("Created default Node from document id " + document.getDocumentId() + " content " + XmlJotter.jotNode(defaultDom));
		}
	} catch (Exception e) {
		throw new WorkflowRuntimeException("Problems creating controller for EDL " + edlAssociation.getEdlName() + " document " + document.getDocumentId(), e);
	}
	return edlController;
}
 
源代码4 项目: keycloak   文件: BaseSAML2BindingBuilder.java
public void signAssertion(Document samlDocument) throws ProcessingException {
    Element originalAssertionElement = org.keycloak.saml.common.util.DocumentUtil.getChildElement(samlDocument.getDocumentElement(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
    if (originalAssertionElement == null) return;
    Node clonedAssertionElement = originalAssertionElement.cloneNode(true);
    Document temporaryDocument;

    try {
        temporaryDocument = org.keycloak.saml.common.util.DocumentUtil.createDocument();
    } catch (ConfigurationException e) {
        throw new ProcessingException(e);
    }

    temporaryDocument.adoptNode(clonedAssertionElement);
    temporaryDocument.appendChild(clonedAssertionElement);

    signDocument(temporaryDocument);

    samlDocument.adoptNode(clonedAssertionElement);

    Element parentNode = (Element) originalAssertionElement.getParentNode();

    parentNode.replaceChild(clonedAssertionElement, originalAssertionElement);
}
 
源代码5 项目: netbeans   文件: PersistenceHelper.java
private void switchToResourceLocalTransaction()  throws IOException {
    Element puElement = helper.findElement(PERSISTENCE_UNIT_TAG);
    puElement.setAttribute(TRANSACTION_TYPE_ATTR, RESOURCE_LOCAL_VALUE);
    
    NodeList nodes = puElement.getElementsByTagName(JTA_DATA_SOURCE_TAG);
    String dataSource = null;
    
    if (nodes.getLength() > 0) {
        Element oldElement = (Element) nodes.item(0);
        dataSource = helper.getValue(oldElement);
        Element newElement = helper.createElement(NON_JTA_DATA_SOURCE_TAG, dataSource);
        puElement.replaceChild(newElement, oldElement);
    }
}
 
源代码6 项目: openjdk-jdk9   文件: NodeTest.java
@Test
public void testReplaceChild() throws Exception {
    Document document = createDOM("Node04.xml");

    Element parentElement = (Element) document.getElementsByTagName("to").item(0);
    Element element = (Element) document.getElementsByTagName("sender").item(0);
    parentElement.replaceChild(createTestDocumentFragment(document), element);

    String outputfile = USER_DIR + "ReplaceChild3.out";
    String goldfile = GOLDEN_DIR + "ReplaceChild3GF.out";
    tryRunWithTmpPermission(() -> outputXml(document, outputfile), new PropertyPermission("user.dir", "read"));
    assertTrue(compareWithGold(goldfile, outputfile));
}
 
源代码7 项目: openjdk-jdk9   文件: NodeTest.java
@Test(expectedExceptions = DOMException.class)
public void testReplaceChildNeg() throws Exception {
    Document document = createDOM("Node04.xml");
    Document doc2 = createNewDocument();

    Element parentElement = (Element) document.getElementsByTagName("to").item(0);
    Element element = (Element) document.getElementsByTagName("sender").item(0);
    parentElement.replaceChild(createTestDocumentFragment(doc2), element);
}
 
源代码8 项目: OpenEstate-IO   文件: OpenImmo_1_2_2.java
/**
 * Downgrade &lt;energiepass&gt; elements to OpenImmo 1.2.1.
 * <p>
 * The &lt;epart&gt; child element of the &lt;energiepass&gt; element is
 * renamed to &lt;art&gt; in version 1.2.1.
 *
 * @param doc OpenImmo document in version 1.2.2
 * @throws JaxenException if xpath evaluation failed
 */
protected void downgradeEnergiepassElements(Document doc) throws JaxenException {
    List nodes = XmlUtils.newXPath(
            "/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass/io:epart",
            doc).selectNodes(doc);
    for (Object item : nodes) {
        Element node = (Element) item;
        Element parentNode = (Element) node.getParentNode();

        Element newNode = doc.createElementNS(StringUtils.EMPTY, "art");
        newNode.setTextContent(node.getTextContent());

        parentNode.replaceChild(newNode, node);
    }
}
 
源代码9 项目: OpenEstate-IO   文件: OpenImmo_1_2_2.java
/**
 * Upgrade &lt;energiepass&gt; elements to OpenImmo 1.2.2.
 * <p>
 * The &lt;art&gt; child element of the &lt;energiepass&gt; element is
 * renamed to &lt;epart&gt; in version 1.2.2.
 *
 * @param doc OpenImmo document in version 1.2.1
 * @throws JaxenException if xpath evaluation failed
 */
protected void upgradeEnergiepassElements(Document doc) throws JaxenException {
    List nodes = XmlUtils.newXPath(
            "/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass/io:art",
            doc).selectNodes(doc);
    for (Object item : nodes) {
        Element node = (Element) item;
        Element parentNode = (Element) node.getParentNode();

        Element newNode = doc.createElementNS(StringUtils.EMPTY, "epart");
        newNode.setTextContent(node.getTextContent());

        parentNode.replaceChild(newNode, node);
    }
}
 
源代码10 项目: jeddict   文件: PersistenceHelper.java
private void switchToResourceLocalTransaction() throws IOException {
    Element puElement = helper.findElement(PERSISTENCE_UNIT_TAG);
    puElement.setAttribute(TRANSACTION_TYPE_ATTR, RESOURCE_LOCAL_VALUE);

    NodeList nodes = puElement.getElementsByTagName(JTA_DATA_SOURCE_TAG);
    String dataSource = null;

    if (nodes.getLength() > 0) {
        Element oldElement = (Element) nodes.item(0);
        dataSource = helper.getValue(oldElement);
        Element newElement = helper.createElement(NON_JTA_DATA_SOURCE_TAG, dataSource);
        puElement.replaceChild(newElement, oldElement);
    }
}
 
源代码11 项目: gwt-eclipse-plugin   文件: XmlUtilities.java
public static void setElementText(IDOMDocument document, Element element,
    String text) {
  Node oldText = element.getFirstChild();
  Text newText = document.createTextNode(text);
  if (oldText != null) {
    element.replaceChild(newText, oldText);
  } else {
    element.appendChild(newText);
  }
}
 
源代码12 项目: gvnix   文件: SecurityServiceImpl.java
/**
 * {@inheritDoc}
 */
public void addOrUpdateAxisClientService(String serviceName,
        Map<String, String> parameters) throws SAXException, IOException {

    createAxisClientConfigFile();
    String axisClientPath = getAxisClientConfigPath();
    Document document = XmlUtils.getDocumentBuilder().parse(
            new File(axisClientPath));

    Element deployment = (Element) document.getFirstChild();

    Element serviceElementDescriptor = getAxisClientService(document,
            serviceName, parameters);

    List<Element> previousServices = XmlUtils.findElements(
            "/deployment/service[@name='".concat(serviceName).concat("']"),
            deployment);

    if (previousServices.isEmpty()) {
        deployment.appendChild(serviceElementDescriptor);
    }
    else {
        deployment.replaceChild(serviceElementDescriptor,
                previousServices.get(0));
    }

    OutputStream outputStream = new ByteArrayOutputStream();

    Transformer transformer = XmlUtils.createIndentingTransformer();

    XmlUtils.writeXml(transformer, outputStream, document);

    fileManager.createOrUpdateTextFileIfRequired(axisClientPath,
            outputStream.toString(), false);

}
 
源代码13 项目: openccg   文件: Disjunctivizer.java
private void processSingletonDifferentPredicate(DLFContext context, LFEdge outgoing,
		LFVertex differentPredicate) {
	LFEdgeLabel label = outgoing.getLabel();
	
	// add relation, then choice point
	Element newRel = addRelation(context, label);
	context.parent = newRel;
	Element choiceElement = addChoice(context);
	context.parent = choiceElement;
	
	// generate the target element, but do not propagate changes to tracked vertices
	Element targetElement = createDisjunctiveElement(context.copy(true));
	
	if(!vertexAliases.containsKey(differentPredicate)) {
		vertexAliases.put(differentPredicate, outgoing.getTarget());
	}
	
	context.vertex = differentPredicate;
	context.parent.appendChild(createDisjunctiveElement(context.copy(true)));
	
	// cleanup: how many new nodes were aliased?
	NodeList newNodes = newRel.getElementsByTagName(NODE_TAG);
	for(int j = 0; j < newNodes.getLength(); j++) {
		if(newNodes.item(j).getAttributes().getNamedItem(IDREF_ATTR) == null) {
			return; // one wasn't aliased
		}
	}
	
	// if we get here, they all were aliased: use generated target element instead
	newRel.replaceChild(targetElement, choiceElement);
}
 
源代码14 项目: pdfxtk   文件: DOMUtils.java
/** Replace the first text element of the given element with a new
     text element containing the given text or just create a new text
     element if there is none to replace.
  
     @param element Element whose text element we want 
     @param text Text to set */

 public static void setTextValue(Element element, String text) {
   Node newTextNode = element.getOwnerDocument().createTextNode(text);

   NodeList childs = element.getChildNodes();
   for (int i = 0; i < childs.getLength(); i++) {
     Node node = childs.item(i);
     if (Node.TEXT_NODE == node.getNodeType()) {
element.replaceChild(newTextNode, node);
return;
     }
   }
   element.appendChild(newTextNode);
 }
 
源代码15 项目: openjdk-jdk9   文件: UserController.java
/**
 * This will check if adoptNode works will adoptNode from
 * @see <a href="content/userInfo.xml">userInfo.xml</a>
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>. This is
 * adopting a node from the XML file which is validated by a DTD and
 * into an XML file which is validated by the schema This covers Row 5
 * for the table
 * http://javaweb.sfbay/~jsuttor/JSR206/jsr-206-html/ch03s05.html. Filed
 * bug 4893745 because there was a difference in behavior.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateUserAccount() throws Exception {
    String userXmlFile = XML_DIR + "userInfo.xml";
    String accountXmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(userXmlFile);
    Element user = (Element) document.getElementsByTagName("FirstName").item(0);
    // Set schema after parsing userInfo.xml. Otherwise it will conflict
    // with DTD validation.
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    DocumentBuilder docBuilder1 = dbf.newDocumentBuilder();
    docBuilder1.setErrorHandler(eh);
    Document accDocument = docBuilder1.parse(accountXmlFile);

    Element firstName = (Element) accDocument
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0);
    Element adoptedAccount = (Element) accDocument.adoptNode(user);

    Element parent = (Element) firstName.getParentNode();
    parent.replaceChild(adoptedAccount, firstName);

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();

    MyDOMOutput mydomoutput = new MyDOMOutput();
    mydomoutput.setByteStream(System.out);

    writer.write(document, mydomoutput);
    writer.write(accDocument, mydomoutput);

    assertFalse(eh.isAnyError());
}
 
源代码16 项目: docx4j-export-FO   文件: XsltFOFunctions.java
/**
   * This is invoked on every paragraph, whether it has a pPr or not.
   * 
   * @param wmlPackage
   * @param pPrNodeIt
   * @param pStyleVal
   * @param childResults - the already transformed contents of the paragraph.
   * @return
   */
  public static DocumentFragment createBlockForPPr( 
  		FOConversionContext context,
  		NodeIterator pPrNodeIt,
  		String pStyleVal, NodeIterator childResults) {
  	
  	DocumentFragment df = createBlock( 
      		context,
      		pPrNodeIt,
      		pStyleVal, childResults,
      		false);  
  	
  	// Arabic (and presumably Hebrew) fix
  	// If we have inline direction="rtl" (created by TextDirection class)
  	// wrap the inline with:
  	//    <bidi-override direction="rtl" unicode-bidi="embed">
/* See further:
	From: Glenn Adams <[email protected]>
	Date: Fri, Mar 21, 2014 at 8:41 AM
	Subject: Re: right align arabic in table-cell
	To: FOP Users <[email protected]>
 */
  	
  	Element block = (Element)df.getFirstChild();
NodeList blockChildren = block.getChildNodes();
  	for (int i = 0 ; i <blockChildren.getLength(); i++ ) {
  	
  		if (blockChildren.item(i) instanceof Element) {
   		Element inline = (Element)blockChildren.item(i);
   	
    	if (inline !=null && inline.getAttribute("direction")!=null
    			&& inline.getAttribute("direction").equals("rtl")) {
	
        	inline.removeAttribute("direction");
    		
    		Element bidiOverride = df.getOwnerDocument().createElementNS("http://www.w3.org/1999/XSL/Format", 
					"fo:bidi-override");
        	bidiOverride.setAttribute("unicode-bidi", "embed" );
        	bidiOverride.setAttribute("direction", "rtl" );    		
    		
        	block.replaceChild(bidiOverride, inline);
        	bidiOverride.appendChild(inline);
    		
    	}
  		}
  	} 
  	
  	if (foContainsElement(block, "leader")) {
	// ptab to leader implementation:
	// for leader to work as expected in fop, we need text-align-last; see http://xmlgraphics.apache.org/fop/faq.html#leader-expansion
	// this code adds that.
  		// Note that it doesn't seem to be necessary for leader in TOC, but it doesn't hurt
	block.setAttribute("text-align-last", "justify");
  	}
  	
  	return df;
  }
 
源代码17 项目: JTAF-XCore   文件: StatementParser.java
private void preprocessStatementList(Element elem, MessageCollector mc)
        throws ParsingException {

    ElementScanner es = new ElementScanner(ParserHelper.getChildren(elem));
    Element next = null;
    // Element tRC =
    // elem.getOwnerDocument().createElement("TryRecoverCleanup");
    if (!elem.getNodeName().equals("TryRecoverCleanup")) {
        while (es.hasNext()) {

            if ((next = es.tryMatch("try")) != null) {
                Element safety = elem.getOwnerDocument().createElement("TryRecoverCleanup");
                Element tryBlock = elem.getOwnerDocument().createElement("try");
                NodeList childNodes = next.getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    tryBlock.appendChild(childNodes.item(i).cloneNode(true));

                }
                elem.replaceChild(safety, next);
                safety.appendChild(tryBlock);

                if ((next = es.tryMatch("recover")) != null) {
                    elem.removeChild(next);
                    Element recoverBlock = elem.getOwnerDocument().createElement("recover");
                    childNodes = next.getChildNodes();
                    for (int i = 0; i < childNodes.getLength(); i++) {
                        recoverBlock.appendChild(childNodes.item(i).cloneNode(true));

                    }
                    safety.appendChild(recoverBlock);
                }

                if ((next = es.tryMatch("cleanup")) != null) {
                    elem.removeChild(next);
                    Element cleanUpBlock = elem.getOwnerDocument().createElement("cleanup");
                    childNodes = next.getChildNodes();
                    for (int i = 0; i < childNodes.getLength(); i++) {
                        cleanUpBlock.appendChild(childNodes.item(i).cloneNode(true));

                    }
                    safety.appendChild(cleanUpBlock);
                }

                continue;
            } else if (((next = es.tryMatch("recover")) != null)
                    || ((next = es.tryMatch("cleanup")) != null)) {
                throw new UnexpectedElementException(next);
            }

            // Move on to the next element
            es.match();
        }
    }
}