List of usage examples for org.w3c.dom Node replaceChild
public Node replaceChild(Node newChild, Node oldChild) throws DOMException;
oldChild
with newChild
in the list of children, and returns the oldChild
node. From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java
/** * Replace the given node with unification element containing unification * representing symbol {@code ◍} (for Presentation MathML, see * {@link Constants#PMATHML_UNIFICATOR}) or {@code ◐} (for Content * MathML, see {@link Constants#CMATHML_UNIFICATOR}). * * @param oldNode The node to be replaced with the unification representing * element.//from ww w .java 2 s . c om * @throws IllegalArgumentException If the given node does not have parent. */ public static void replaceNodeWithUnificator(Node oldNode) { Node parentNode = oldNode.getParentNode(); if (parentNode == null) { throw new IllegalArgumentException("Cannot replace node [" + oldNode + "] that has no parent."); } else { if (!Constants.CMATHML_ANNOTATIONS.contains(oldNode.getNodeName())) { // Do not modify annotation elements! String unificator = PMATHML_UNIFICATOR; String unificatorElementType = oldNode.getNodeName().equals(PMATHML_OPERATOR) ? PMATHML_OPERATOR : PMATHML_IDENTIFIER; if (MathMLTools.isContentMathMLNode(oldNode)) { unificator = CMATHML_UNIFICATOR; unificatorElementType = Constants.CMATHML_IDENTIFIER_OR_NUMBER.contains(oldNode.getNodeName()) ? CMATHML_IDENTIFIER : CMATHML_SYMBOL; } Node newNode = oldNode.getOwnerDocument().createElementNS(oldNode.getNamespaceURI(), unificatorElementType); newNode.setTextContent(unificator); parentNode.replaceChild(newNode, oldNode); } } }
From source file:com.photon.phresco.impl.ConfigManagerImpl.java
@Override public void updateConfiguration(String envName, String oldConfigName, Configuration configuration) throws ConfigurationException { Node environment = getNode(getXpathEnv(envName).toString()); Node oldConfigNode = getNode(getXpathConfigByEnv(envName, oldConfigName)); Element configElement = createConfigElement(configuration); environment.replaceChild(configElement, oldConfigNode); try {// w w w. j a v a2s . c o m writeXml(new FileOutputStream(configFile)); } catch (FileNotFoundException e) { throw new ConfigurationException(e); } }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.WsdlMimeMessageResponse.java
private void expandMtomAttachments(WsdlRequest wsdlRequest) { try {/*from ww w . ja va 2 s . c o m*/ // XmlObject xmlObject = XmlObject.Factory.parse( getContentAsString() // ); XmlObject xmlObject = XmlUtils.createXmlObject(getContentAsString()); XmlObject[] includes = xmlObject .selectPath("declare namespace xop='http://www.w3.org/2004/08/xop/include'; //xop:Include"); for (XmlObject include : includes) { Element elm = (Element) include.getDomNode(); String href = elm.getAttribute("href"); Attachment attachment = getMmSupport().getAttachmentWithContentId("<" + href.substring(4) + ">"); if (attachment != null) { ByteArrayOutputStream data = Tools.readAll(attachment.getInputStream(), 0); byte[] byteArray = data.toByteArray(); XmlCursor cursor = include.newCursor(); cursor.toParent(); XmlObject parentXmlObject = cursor.getObject(); cursor.dispose(); SchemaType schemaType = parentXmlObject.schemaType(); Node parentNode = elm.getParentNode(); if (schemaType.isNoType()) { SchemaTypeSystem typeSystem = wsdlRequest.getOperation().getInterface().getWsdlContext() .getSchemaTypeSystem(); SchemaGlobalElement schemaElement = typeSystem .findElement(new QName(parentNode.getNamespaceURI(), parentNode.getLocalName())); if (schemaElement != null) { schemaType = schemaElement.getType(); } } String txt = null; if (SchemaUtils.isInstanceOf(schemaType, XmlHexBinary.type)) { txt = new String(Hex.encodeHex(byteArray)); } else { txt = new String(Base64.encodeBase64(byteArray)); } parentNode.replaceChild(elm.getOwnerDocument().createTextNode(txt), elm); } } getMmSupport().setResponseContent(xmlObject.toString()); } catch (Exception e) { SoapUI.logError(e); } }
From source file:jef.tools.XMLUtils.java
/** * ???/*from w w w. j ava 2 s .c om*/ * * @param node * * @param tagName * ?? * @param nodeText * * @return Element */ public static Element replaceElement(Node node, String tagName, String... nodeText) { Node pNode = node.getParentNode(); Assert.notNull(pNode); Document doc = null; if (node.getNodeType() == Node.DOCUMENT_NODE) { doc = (Document) node; } else { doc = node.getOwnerDocument(); } Element e = doc.createElement(tagName); if (nodeText.length == 1) { setText(e, nodeText[0]); } else if (nodeText.length > 1) { setText(e, StringUtils.join(nodeText, '\n')); } pNode.replaceChild(e, node); return e; }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Substitute the element selected by the xPath in the given node with the new node. * /*from w ww.j a v a 2 s.co m*/ * @param node * The node. * @param xPath * The xPath. * @param newNode * The new node. * @return The resulting node after the substitution. * @throws Exception * If anything fails. */ public static Node substitute(final Node node, final String xPath, final Node newNode) throws Exception { Node result = node; Node replace = selectSingleNode(result, xPath); assertNotNull("No node selected for substitute. ", replace); Node parent = replace.getParentNode(); parent.replaceChild(newNode, replace); return result; }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ClinicalDateObscurer.java
/** * This methods goes through the original XML document and obscure a few selected dates by changing the time reference * to a chosen Date element in the XML./*from w w w . j a v a2 s. c om*/ * * @param document the XML DOM Document * @param xpath an XPath instance * @param basisYear the new time reference year * @param basisMonth the new time reference month * @param basisDay the new time reference day * @param basisPrecision the time reference precision * @param ageAtBasisDate the age of the patient based on the new time reference * @param patientBirthYearAttributes the birth year attributes for the patient * @param bcrPatientOverCutoffAgeBarcodeList a list to store the barcode of patient whose age is over the cutoff age * @return the Document with the dates to be obscured replaced by an elapsed time since the new time reference * @throws ProcessorException */ private Document obscureElements(final Document document, final XPath xpath, final String basisYear, final String basisMonth, final String basisDay, final String basisPrecision, final long ageAtBasisDate, final Hashtable<String, String> patientBirthYearAttributes, final List<String> bcrPatientOverCutoffAgeBarcodeList) throws ProcessorException { //Iterate on the list of element's name suffixes to validate the different dates final Map<String, String> datesToObscure = getDatesToObscure(document, xpath); final Iterator<String> xpathSuffixIterator = datesToObscure.keySet().iterator(); String xpathSuffix = null; while (xpathSuffixIterator.hasNext()) { xpathSuffix = xpathSuffixIterator.next(); String elementNamePrefix = getElapsedElementBase(); String elementNameSuffix = xpathSuffix; String namespacePrefix = null; int indexOfColon = xpathSuffix.indexOf(":"); if (indexOfColon > 0) { elementNameSuffix = xpathSuffix.substring(indexOfColon + 1); namespacePrefix = xpathSuffix.substring(0, indexOfColon); } if (namespacePrefix == null || xpath.getNamespaceContext().getNamespaceURI(namespacePrefix) != null) { try { final String yearOfNodesAttributesExpression = getXPathExpressionIgnoringNamespace(yearOfPrefix, xpathSuffix); final String monthOfNodesAttributesExpression = getXPathExpressionIgnoringNamespace( monthOfPrefix, xpathSuffix); final String dayOfNodesAttributesExpression = getXPathExpressionIgnoringNamespace(dayOfPrefix, xpathSuffix); final NodeList yearOfNodes = getNodeListFromXPathExpression(document, xpath, yearOfNodesAttributesExpression); final NodeList monthOfNodes = getNodeListFromXPathExpression(document, xpath, monthOfNodesAttributesExpression); final NodeList dayOfNodes = getNodeListFromXPathExpression(document, xpath, dayOfNodesAttributesExpression); // must have the same number of year, month, and day nodes if (yearOfNodes.getLength() != monthOfNodes.getLength()) { throw new ProcessorException( getNodeListLengthMismatchErrorMessage(yearOfNodesAttributesExpression, monthOfNodesAttributesExpression, yearOfNodes, monthOfNodes)); } if (yearOfNodes.getLength() != dayOfNodes.getLength()) { throw new ProcessorException( getNodeListLengthMismatchErrorMessage(yearOfNodesAttributesExpression, dayOfNodesAttributesExpression, yearOfNodes, dayOfNodes)); } //Iterate through the selected element names that need to be obscured and obscure the dates for (int nodeIndex = 0; nodeIndex < yearOfNodes.getLength(); nodeIndex++) { final Node yearOfNode = yearOfNodes.item(nodeIndex); final Node monthOfNode = monthOfNodes.item(nodeIndex); final Node dayOfNode = dayOfNodes.item(nodeIndex); final Node parentNode = yearOfNode.getParentNode(); final String yearOf = yearOfNode.getTextContent().trim(); final String monthOf = monthOfNode.getTextContent().trim(); final String dayOf = dayOfNode.getTextContent().trim(); String monthOfProcurementStatus = null; String yearOfOwner = null; String yearOfProcurementStatus = null; final Node yearOfProcurementStatusNode = yearOfNode.getAttributes() .getNamedItem(PROCUREMENT_STATUS); if (yearOfProcurementStatusNode != null) { yearOfProcurementStatus = yearOfProcurementStatusNode.getTextContent().trim(); } final Node yearOfOwnerNode = yearOfNode.getAttributes().getNamedItem(OWNER); if (yearOfOwnerNode != null) { yearOfOwner = yearOfOwnerNode.getTextContent().trim(); } final Node monthOfProcurementStatusNode = monthOfNode.getAttributes() .getNamedItem(PROCUREMENT_STATUS); if (monthOfProcurementStatusNode != null) { monthOfProcurementStatus = monthOfProcurementStatusNode.getTextContent().trim(); } if (parentNode != null) { // find the namespace from the yearOf node String namespace = ""; String yearNodeName = yearOfNode.getNodeName(); if (yearNodeName.contains(":")) { namespace = yearNodeName.substring(0, yearNodeName.indexOf(":") + 1); // include the ':' } //Update document //Replace dayOfPrefix node by elapsedElementBase node String elementValue = ""; String cdeAttributeValue = datesToObscure.get(xpathSuffix); String ownerAttributeValue = yearOfOwner; String elementPrecision = getPrecisionForElementDate(yearOf, monthOf, dayOf, basisPrecision); boolean elementValueFloored = false; if (elementPrecision.equals(PRECISION_YEAR) || elementPrecision.equals("")) { // set precision to empty since we are not going to do the calculation elementPrecision = ""; } else { Date elementDate = makeDateFromParts(yearOf, monthOf, dayOf, elementPrecision); Date basisDate = makeDateFromParts(basisYear, basisMonth, basisDay, elementPrecision); Long elapsedDays = calculateElapsedDaysBetween(elementDate, basisDate); //The 'days to birth' value needs to be floored if it's lower than a lower bound if (xpathSuffix.equals(getBirthDateName()) && elapsedDays < getDaysToBirthLowerBound()) { elapsedDays = getDaysToBirthLowerBound().longValue(); elementValueFloored = true; } elementValue = (elapsedDays == null ? null : String.valueOf(elapsedDays)); } // Procurement status should be set to 'Completed' if the element has a non blank value, // otherwise it should be set to the year of's procurement status final String procurementStatusAttributeValue = StringUtils.isBlank(elementValue) ? yearOfProcurementStatus : ProcurementStatus.Completed.toString(); final Node yearOfNodeTierAttribute = yearOfNode.getAttributes().getNamedItem(TIER); final String tierAttributeValue = (yearOfNodeTierAttribute != null ? yearOfNodeTierAttribute.getTextContent().trim() : null); String xsdVerAttribute = getXsdVersionAttributeValue(yearOfNode); final String precisionAttributeValue = elementPrecision; Node daysToNode = createElementNode(document, namespace + elementNamePrefix, elementNameSuffix, elementValue, cdeAttributeValue, ownerAttributeValue, procurementStatusAttributeValue, tierAttributeValue, xsdVerAttribute, precisionAttributeValue, elementValueFloored); parentNode.replaceChild(daysToNode, dayOfNode); //Remove monthOfPrefix node if <code>xpathSuffix</code> is different from <code>basisDateNameForClinical</code>, //otherwise replace it by a new ageAtPrefix + <code>basisDateNameForClinical</code> Element if (!xpathSuffix.equals(getBasisDateNameForClinical())) { removeChildNode(parentNode, monthOfNode); } else { boolean ageAtBasisDateValueFloored = false; String ageAtBasisDateValue = ""; if (ageAtBasisDate != -1) { if (ageAtBasisDate > getCutoffAgeAtInitialDiagnosis()) { ageAtBasisDateValue = getCutoffAgeAtInitialDiagnosis().toString(); // the patient's age > cutoff age, floor it at the cutoff age ageAtBasisDateValueFloored = true; //add the patient barcode to the list of patient whose age is over the cutoff age bcrPatientOverCutoffAgeBarcodeList .add(getBcrPatientBarcode(document, xpath)); } else { ageAtBasisDateValue = String.valueOf(ageAtBasisDate); } } final String ageAtOwnerAttributeValue = patientBirthYearAttributes.get(OWNER); final String yearOfBirthProcurementStatus = patientBirthYearAttributes .get(PROCUREMENT_STATUS); // Procurement status should be set to 'Completed' if the element has a non blank value, // otherwise it should be set to the patient year of birth's procurement status final String ageAtProcurementStatusAttributeValue = StringUtils .isBlank(ageAtBasisDateValue) ? yearOfBirthProcurementStatus : ProcurementStatus.Completed.toString(); final String ageAtTierAttributeValue = patientBirthYearAttributes.get(TIER); final String monthOfNodeNamespace = getNamespaceFromNodeName(monthOfNode); final Node ageAtNode = createElementNode(document, monthOfNodeNamespace + ageAtPrefix, elementNameSuffix, ageAtBasisDateValue, ageAtBasisDateCDE, ageAtOwnerAttributeValue, ageAtProcurementStatusAttributeValue, ageAtTierAttributeValue, xsdVerAttribute, null, ageAtBasisDateValueFloored); parentNode.replaceChild(ageAtNode, monthOfNode); } //Remove yearOfPrefix node if: // <code>xpathSuffix</code> is different from <code>basisDateNameForClinical</code> if (!xpathSuffix.equals(getBasisDateNameForClinical())) { removeChildNode(parentNode, yearOfNode); } } else { final String xMsg = "The Parent Node is null for the XPath expression: " + yearOfPrefix + xpathSuffix + "[" + nodeIndex + "]"; throw new ProcessorException(xMsg); } } } catch (XPathExpressionException x) { throw new ProcessorException("Xpath Expression error", x); } } // else this date is in a namespace not in this document, so skip it, since it must not be in here (or would have failed validation) } return document; }
From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java
/***** * Adds a new node or replaces an existing node in the Document * /*ww w.j a va2 s . c o m*/ * @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())) { // 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); } }
From source file:org.apache.ode.bpel.rtrep.v1.ASSIGN.java
private Element replaceElement(Element lval, Element ptr, Element src, boolean keepSrcElement) { Document doc = ptr.getOwnerDocument(); Node parent = ptr.getParentNode(); if (keepSrcElement) { Element replacement = (Element) doc.importNode(src, true); parent.replaceChild(replacement, ptr); return (lval == ptr) ? replacement : lval; }/*from w w w. j av a 2s .co m*/ Element replacement = doc.createElementNS(ptr.getNamespaceURI(), ptr.getLocalName()); NodeList nl = src.getChildNodes(); for (int i = 0; i < nl.getLength(); ++i) replacement.appendChild(doc.importNode(nl.item(i), true)); NamedNodeMap attrs = src.getAttributes(); for (int i = 0; i < attrs.getLength(); ++i) { Attr attr = (Attr) attrs.item(i); if (!attr.getName().startsWith("xmlns")) { replacement.setAttributeNodeNS((Attr) doc.importNode(attrs.item(i), true)); // Case of qualified attribute values, we're forced to add corresponding namespace declaration manually int colonIdx = attr.getValue().indexOf(":"); if (colonIdx > 0) { String prefix = attr.getValue().substring(0, colonIdx); String attrValNs = src.lookupPrefix(prefix); if (attrValNs != null) replacement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + prefix, attrValNs); } } } parent.replaceChild(replacement, ptr); DOMUtils.copyNSContext(ptr, replacement); return (lval == ptr) ? replacement : lval; }
From source file:org.apache.ode.bpel.rtrep.v2.ASSIGN.java
private Element replaceElement(Element lval, Element ptr, Element src, boolean keepSrcElement) { Document doc = ptr.getOwnerDocument(); Node parent = ptr.getParentNode(); if (keepSrcElement) { Element replacement = (Element) doc.importNode(src, true); parent.replaceChild(replacement, ptr); return (lval == ptr) ? replacement : lval; }/* w w w .java 2 s . c o m*/ Element replacement = doc.createElementNS(ptr.getNamespaceURI(), ptr.getLocalName()); if (ptr.getPrefix() != null) { replacement.setPrefix(ptr.getPrefix()); } NodeList nl = src.getChildNodes(); for (int i = 0; i < nl.getLength(); ++i) replacement.appendChild(doc.importNode(nl.item(i), true)); NamedNodeMap attrs = src.getAttributes(); for (int i = 0; i < attrs.getLength(); ++i) { Attr attr = (Attr) attrs.item(i); if (!attr.getName().startsWith("xmlns")) { replacement.setAttributeNodeNS((Attr) doc.importNode(attrs.item(i), true)); // Case of qualified attribute values, we're forced to add corresponding namespace declaration manually int colonIdx = attr.getValue().indexOf(":"); if (colonIdx > 0) { String prefix = attr.getValue().substring(0, colonIdx); String attrValNs = src.lookupPrefix(prefix); if (attrValNs != null) replacement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + prefix, attrValNs); } } } parent.replaceChild(replacement, ptr); DOMUtils.copyNSContext(ptr, replacement); return (lval == ptr) ? replacement : lval; }