Java Code Examples for org.w3c.dom.Element#replaceChild()
The following examples show how to use
org.w3c.dom.Element#replaceChild() .
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: BaseSAML2BindingBuilder.java From keycloak with Apache License 2.0 | 6 votes |
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); }
Example 2
Source File: EDLControllerFactory.java From rice with Educational Community License v2.0 | 6 votes |
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; }
Example 3
Source File: TestSummary.java From caja with Apache License 2.0 | 6 votes |
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; }
Example 4
Source File: XmlUtils.java From OpenEstate-IO with Apache License 2.0 | 6 votes |
/** * 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)); } } }
Example 5
Source File: PersistenceHelper.java From jeddict with Apache License 2.0 | 5 votes |
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); } }
Example 6
Source File: DOMUtils.java From pdfxtk with Apache License 2.0 | 5 votes |
/** 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); }
Example 7
Source File: Disjunctivizer.java From openccg with GNU Lesser General Public License v2.1 | 5 votes |
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); }
Example 8
Source File: SecurityServiceImpl.java From gvnix with GNU General Public License v3.0 | 5 votes |
/** * {@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); }
Example 9
Source File: XmlUtilities.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
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); } }
Example 10
Source File: PersistenceHelper.java From netbeans with Apache License 2.0 | 5 votes |
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); } }
Example 11
Source File: OpenImmo_1_2_2.java From OpenEstate-IO with Apache License 2.0 | 5 votes |
/** * Upgrade <energiepass> elements to OpenImmo 1.2.2. * <p> * The <art> child element of the <energiepass> element is * renamed to <epart> 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); } }
Example 12
Source File: OpenImmo_1_2_2.java From OpenEstate-IO with Apache License 2.0 | 5 votes |
/** * Downgrade <energiepass> elements to OpenImmo 1.2.1. * <p> * The <epart> child element of the <energiepass> element is * renamed to <art> 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); } }
Example 13
Source File: NodeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@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); }
Example 14
Source File: NodeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@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)); }
Example 15
Source File: StatementParser.java From JTAF-XCore with Apache License 2.0 | 4 votes |
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(); } } }
Example 16
Source File: XsltFOFunctions.java From docx4j-export-FO with Apache License 2.0 | 4 votes |
/** * 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; }
Example 17
Source File: UserController.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * 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()); }