/** * Update magento db connection details in local.xml * * @param magentoDbHost * @param magentoDbUser * @param magentoDbPasswd * @param magentoDbName * @param payload */ public static void updateDbValues( String magentoDbHost, String magentoDbUser, String magentoDbPasswd, String magentoDbName, Document payload) { // get <connection> nodes final NodeList connectionNodes = payload.getElementsByTagName("connection"); // update database settings for each <connection> block for (int i = 0; i < connectionNodes.getLength(); i++) { Node n = connectionNodes.item(i); NodeList dbNodes = n.getChildNodes(); for (int j = 0; j < dbNodes.getLength(); j++) { Node dbNode = dbNodes.item(j); NodeList cdataNodes = dbNode.getChildNodes(); CDATASection cdata = null; switch (dbNode.getNodeName()) { case "host": dbNodes.item(j).setNodeValue(""); while (cdataNodes.getLength() > 0) { dbNode.removeChild(cdataNodes.item(0)); } cdata = payload.createCDATASection(magentoDbHost); dbNodes.item(j).appendChild(cdata); break; case "username": dbNodes.item(j).setNodeValue(""); while (cdataNodes.getLength() > 0) { dbNode.removeChild(cdataNodes.item(0)); } cdata = payload.createCDATASection(magentoDbUser); dbNodes.item(j).appendChild(cdata); break; case "password": dbNodes.item(j).setNodeValue(""); while (cdataNodes.getLength() > 0) { dbNode.removeChild(cdataNodes.item(0)); } if (magentoDbPasswd == null) { magentoDbPasswd = ""; } cdata = payload.createCDATASection(magentoDbPasswd); dbNodes.item(j).appendChild(cdata); break; case "dbname": dbNodes.item(j).setNodeValue(""); while (cdataNodes.getLength() > 0) { dbNode.removeChild(cdataNodes.item(0)); } cdata = payload.createCDATASection(magentoDbName); dbNodes.item(j).appendChild(cdata); break; } } } }
@Override public Object invokeXpathProjection( final InvocationContext invocationContext, final Object proxy, final Object[] args) throws Throwable { // try { // if (ReflectionHelper.mayProvideParameterNames()) { // xPath.setXPathVariableResolver(new MethodParamVariableResolver(method, // args, xPath.getXPathVariableResolver())); // } final XPathExpression expression = invocationContext.getxPathExpression(); NodeList nodes = (NodeList) expression.evaluate(node, XPathConstants.NODESET); int count = 0; for (int i = 0; i < nodes.getLength(); ++i) { if (Node.ATTRIBUTE_NODE == nodes.item(i).getNodeType()) { Attr attr = (Attr) nodes.item(i); attr.getOwnerElement().removeAttributeNode(attr); ++count; continue; } Node parentNode = nodes.item(i).getParentNode(); if (parentNode == null) { continue; } parentNode.removeChild(nodes.item(i)); ++count; } return getProxyReturnValueForMethod(proxy, method, Integer.valueOf(count)); // } finally { // xPath.reset(); // } }
/** * Parses a string containing XML and returns a DocumentFragment containing the nodes of the * parsed XML. */ public static void loadFragment(Element el, String fragment) { // Wrap the fragment in an arbitrary element fragment = "<fragment>" + fragment + "</fragment>"; try { // Create a DOM builder and parse the fragment DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(fragment))); Document doc = el.getOwnerDocument(); // Import the nodes of the new document into doc so that they // will be compatible with doc Node node = doc.importNode(d.getDocumentElement(), true); // Create the document fragment node to hold the new nodes DocumentFragment docfrag = doc.createDocumentFragment(); // Move the nodes into the fragment while (node.hasChildNodes()) { el.appendChild(node.removeChild(node.getFirstChild())); } } catch (Exception e) { log.error(e, e); } }
/** * Update an application in the manifest * * @param app app to replace for */ public void updateApplication(PhoneLabApplication app) { try { Node node = (Node) xpath.evaluate( "/manifest/statusmonitor/parameter[@package_name='" + app.getPackageName() + "']", document, XPathConstants.NODE); if (node != null) { // exist Node parentNode = node.getParentNode(); parentNode.removeChild(node); Element newElement = document.createElement("application"); if (app.getPackageName() != null) newElement.setAttribute("package_name", app.getPackageName()); if (app.getName() != null) newElement.setAttribute("name", app.getName()); if (app.getDescription() != null) newElement.setAttribute("description", app.getDescription()); if (app.getType() != null) newElement.setAttribute("type", app.getType()); if (app.getStartTime() != null) newElement.setAttribute("start_time", app.getStartTime()); if (app.getEndTime() != null) newElement.setAttribute("end_time", app.getEndTime()); if (app.getDownload() != null) newElement.setAttribute("download", app.getDownload()); if (app.getVersion() != null) newElement.setAttribute("version", app.getVersion()); if (app.getAction() != null) newElement.setAttribute("action", app.getAction()); document.getFirstChild().appendChild(newElement); } } catch (XPathExpressionException e) { e.printStackTrace(); } }
public static void removeChildren(Node node) { if (node != null) { while (node.hasChildNodes()) { node.removeChild(node.getFirstChild()); } } }
public static void removeTextNodes(Node node) { NodeList nl = node.getChildNodes(); int i = 0; while (i < nl.getLength()) if (nl.item(i).getNodeType() == Node.TEXT_NODE) node.removeChild(nl.item(i)); else i++; }
public static void removeNodesByName(Node node, String name) { NodeList nl = node.getChildNodes(); int i = 0; while (i < nl.getLength()) if (nl.item(i).getNodeName().equals(name)) node.removeChild(nl.item(i)); else i++; }
/** * Update base url details in local.xml.phpunit * * @param magentoDbHost * @param magentoDbUser * @param magentoDbPasswd * @param magentoDbName * @param payload */ public static void updateBaseUrls( String baseUrlUnsecure, String baseUrlSecure, boolean seoRewrites, Document payload) { // get <secure> nodes final NodeList secureNodes = payload.getElementsByTagName("secure"); for (int i = 0; i < secureNodes.getLength(); i++) { NodeList urlNodes = secureNodes.item(i).getChildNodes(); for (int j = 0; j < urlNodes.getLength(); j++) { Node urlNode = urlNodes.item(j); NodeList cdataNodes = urlNode.getChildNodes(); CDATASection cdata = null; switch (urlNode.getNodeName()) { case "base_url": urlNodes.item(j).setNodeValue(""); while (cdataNodes.getLength() > 0) { urlNode.removeChild(cdataNodes.item(0)); } cdata = payload.createCDATASection(MagentoUtil.validateBaseUrl(baseUrlSecure, true)); urlNodes.item(j).appendChild(cdata); break; } } } // get <unsecure> nodes final NodeList unsecureNodes = payload.getElementsByTagName("unsecure"); for (int i = 0; i < unsecureNodes.getLength(); i++) { NodeList urlNodes = unsecureNodes.item(i).getChildNodes(); for (int j = 0; j < urlNodes.getLength(); j++) { Node urlNode = urlNodes.item(j); NodeList cdataNodes = urlNode.getChildNodes(); CDATASection cdata = null; switch (urlNode.getNodeName()) { case "base_url": urlNodes.item(j).setNodeValue(""); while (cdataNodes.getLength() > 0) { urlNode.removeChild(cdataNodes.item(0)); } cdata = payload.createCDATASection(MagentoUtil.validateBaseUrl(baseUrlUnsecure, false)); urlNodes.item(j).appendChild(cdata); break; } } } }
public void detachNode() { Node parent = getParentNode(); if (parent != null) { parent.removeChild(this); } encodingStyleAttribute.clearNameAndValue(); // Fix for CR: 6474641 // tryToFindEncodingStyleAttributeName(); }
private void removeNodes(NodeList nl) { int count = nl.getLength(); for (int i = 0; i < count; i++) { Node node = nl.item(i); Node parent = node.getParentNode(); if (parent == null) continue; parent.removeChild(node); } }
public boolean setNodeText(Document domDocument, Node n, String value) { if (n == null) return false; Node nc = null; while ((nc = n.getFirstChild()) != null) { n.removeChild(nc); } n.appendChild(domDocument.createTextNode(value)); return true; }
/** * removes all comments from a node * * @param node node to remove elements from * @param type Type Definition to remove (Constant value from class Node) * @param deep remove also in sub nodes */ private static synchronized void removeChilds(Node node, short type, boolean deep) { NodeList list = node.getChildNodes(); for (int i = list.getLength(); i >= 0; i--) { Node n = list.item(i); if (n == null) continue; else if (n.getNodeType() == type) node.removeChild(XMLCaster.toRawNode(n)); else if (deep) removeChilds(n, type, deep); } }
public void update() { try { File pomFile = new File(getFile(), "pom.xml"); XPathEvaluator xpath = new XPathEvaluator(pomFile); // fix kie version if needed due to SWITCHYARD-2834 Node node = xpath.evaluateNode( "/project/build/plugins/plugin/executions/execution/configuration/versions/switchyard.osgi.version"); if (node != null) { node.setTextContent("${switchyard.version}"); } // fix bpm and rules groupId String kieVersion = xpath.evaluateString("/project/properties/kie.version"); if (kieVersion != null && kieVersion.startsWith("6.4.0")) { node = xpath.evaluateNode( "/project/dependencies/dependency[artifactId='switchyard-component-bpm']/groupId"); if (node != null) { node.setTextContent("org.jboss.integration.fuse"); } node = xpath.evaluateNode( "/project/dependencies/dependency[artifactId='switchyard-component-rules']/groupId"); if (node != null) { node.setTextContent("org.jboss.integration.fuse"); } } // fix order of boms node = xpath.evaluateNode( "/project/dependencyManagement/dependencies/dependency[artifactId='switchyard-bom']"); if (node != null) { Node parentNode = node.getParentNode(); parentNode.removeChild(node); parentNode.appendChild(node); } // save the changes xpath.printDocument(new StreamResult(pomFile)); } catch (Throwable e) { throw new RuntimeException(e); } select(); new ContextMenu("Maven", "Update Project...").select(); new DefaultShell("Update Maven Project"); new CheckBox("Force Update of Snapshots/Releases").toggle(true); new PushButton("OK").click(); AbstractWait.sleep(TimePeriod.NORMAL); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); }
/** * Removes all child nodes from the context node. * * @param contextNode Node whose children needs to be removed */ public static void removeChildNodes(Node contextNode) { try { NodeList nodeList = contextNode.getChildNodes(); while (nodeList.getLength() > 0) { contextNode.removeChild(nodeList.item(0)); } } catch (DOMException de) { } }
/** * This will remove all applications * * @throws XPathExpressionException */ public void removeAllApplications() throws XPathExpressionException { Node rootElement = document.getFirstChild(); if (rootElement != null) { NodeList list = (NodeList) xpath.evaluate("/manifest/application", document, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); rootElement.removeChild(node); } } }
private void removeSpaces(Node node) { NodeList childNodesList = node.getChildNodes(); for (int i = childNodesList.getLength() - 1; i >= 0; i--) { Node child = childNodesList.item(i); if (child instanceof Text && ((Text) child).getData().trim().length() == 0) { node.removeChild(child); } else if (child instanceof Element) { removeSpaces(child); } } }
public void trimChild(Node node, Node child) { if (child instanceof Text) { if (isNullOrEmpty(child.getNodeValue().trim())) { node.removeChild(child); } return; } if (child instanceof Element) { trimNode(child); } }
private static void trimWhitespaceTextNodes(final org.w3c.dom.Node node) { if (node != null && node.hasChildNodes()) { for (int i = 0; i < node.getChildNodes().getLength(); i++) { final org.w3c.dom.Node child = node.getChildNodes().item(i); if (child.getNodeType() == org.w3c.dom.Node.TEXT_NODE && child.getNodeValue().trim().length() == 0) { node.removeChild(child); } trimWhitespaceTextNodes(node.getChildNodes().item(i)); } } }
public File stripXmlFromFile(File xmlFile) throws ParserConfigurationException, IOException, SAXException, TransformerException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = null; doc = db.parse(xmlFile); // doc.getDocumentElement().normalize(); try { System.out.println("Root element " + doc.getDocumentElement().getNodeName()); NodeList nodeLst = doc.getElementsByTagName("sv:property"); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); System.out.println(fstNode.getNodeName()); Element fstElmnt = (Element) fstNode; String attribute = fstElmnt.getAttribute("sv:name"); if (attribute.equals("jcr:uuid")) { Node parent = fstElmnt.getParentNode(); parent.removeChild(fstElmnt); } } } catch (Exception e) { System.out.println(e.getMessage()); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "no"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); System.out.println(xmlString); File parsedXml = new File("./src/test/resources/htmltagstripper/result.xml"); if (parsedXml.exists()) { boolean deleted = parsedXml.delete(); } FileWriter fileWriter = new FileWriter(parsedXml); fileWriter.write(result.getWriter().toString()); fileWriter.flush(); return parsedXml; }
/** * Remove an application based on package name * * @param packageName * @throws XPathExpressionException */ public void removeApplication(String packageName) throws XPathExpressionException { Node rootElement = document.getFirstChild(); NodeList list = (NodeList) xpath.evaluate( "/manifest/application[@package_name='" + packageName + "']", document, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); rootElement.removeChild(node); } }
/** * Copy old node's children to newNode.If the newNode is the father of the old node,then the old * node's children will be inserted before the old node,otherwise,the old node's children just * append to the newNode. * * @param old * @param newNode */ public static void copyChildren(Node old, Node newNode) { Node child = old.getFirstChild(); while (child != null) { Node next = child.getNextSibling(); child = old.removeChild(child); if (old.getParentNode() == newNode) { newNode.insertBefore(child, old); } else { newNode.appendChild(child); } child = next; } }
private void setXmlEntry(Document doc, Node opSet) { NodeList targetNodes = findNodes(doc, opSet); NodeList valueNodes = getValueNodes(opSet); if (targetNodes == null) { return; } int targetNodesCount = targetNodes.getLength(); for (int i = 0; i < targetNodesCount; i++) { Node target = targetNodes.item(i); for (Node child; (child = target.getFirstChild()) != null; target.removeChild(child)) ; appendNodes(doc, target, valueNodes); } }
private void removeNode(Element node) { if (imageDefaults == null) { imageDefaults = getImageDefaults(); } Node parent = node.getParentNode(); parent.removeChild(node); makeXmlTree(); try { imageDefaults.writeWritable(); } catch (Exception e) { logger.error("write error!", e); } imageDefaults.setWritableDocument(imageDefaultsDocument, imageDefaultsRoot); }
/** * {@inheritDoc} In case children were to be removed between the time when this Change was added, * and the time when it was applied, maybe due to application of a RemoveChildrenChange, such * children are not re-instated. In case children were to be added between the time when this * Change was added, and the time when it was applied, maybe due to application of an * AddChildChange, such children are appended to the end of the list in preserving the order in * which they were added (that is they appear at the end). */ public void changeDocument(Node componentNode) { // build order map of of current Nodes, keyed by id LinkedHashMap<String, Node> currChildrenMap = new LinkedHashMap<String, Node>(13); Node currChild = componentNode.getFirstChild(); int fakeIndex = 0; while (currChild != null) { NamedNodeMap attributes = currChild.getAttributes(); String currKey = null; if (attributes != null) { Node idAttr = attributes.getNamedItem(_identifier); if (idAttr != null) { currKey = idAttr.getNodeValue(); } } // create a dummy key to maintain order of non-ided children if (currKey == null) { // =-= bts What about insignificant whitespace? currKey = Integer.valueOf(fakeIndex++).toString(); } currChildrenMap.put(currKey, currChild); // remove the children so that we can add them back in componentNode.removeChild(currChild); // next node is first node again currChild = componentNode.getFirstChild(); } // // put children back in, in order // for (String currReorderID : _childIds) { currChild = currChildrenMap.remove(currReorderID); if (currChild != null) { componentNode.appendChild(currChild); } } // add in all of the rest of the children in // relative order they originally appeared for (Map.Entry<String, Node> entry : currChildrenMap.entrySet()) { componentNode.appendChild(entry.getValue()); } }
/** * Removes all the immediate child text nodes. * * @param parent the parent * @return the element */ private static Node removeTextNodes(Node parent) { Node result = parent; NodeList nodeList = parent.getChildNodes(); int nodeListSize = nodeList.getLength(); for (int i = 0; i < nodeListSize; i++) { Node child = nodeList.item(i); if (child != null && child.getNodeType() == Node.TEXT_NODE) { parent.removeChild(child); } } return result; }
private void replaceXmlEntry(Document doc, Node opReplace) { NodeList targetNodes = findNodes(doc, opReplace); NodeList valueNodes = getValueNodes(opReplace); if (targetNodes == null) { return; } int targetNodesCount = targetNodes.getLength(); for (int i = 0; i < targetNodesCount; i++) { Node target = targetNodes.item(i); Node parent = target.getParentNode(); if (parent == null) continue; parent.removeChild(target); appendNodes(doc, parent, valueNodes); } }
/** * Removes comments and processing instruction, and then unites adjacent text nodes. Note that * CDATA sections count as text nodes. */ public static void simplify(Node node) { NodeList children = node.getChildNodes(); int i = 0; int len = children.getLength(); Node prevTextChild = null; while (i < len) { Node child = children.item(i); if (child.hasChildNodes()) { simplify(child); prevTextChild = null; i++; } else { int type = child.getNodeType(); if (type == Node.PROCESSING_INSTRUCTION_NODE) { node.removeChild(child); len--; } else if (type == Node.COMMENT_NODE) { node.removeChild(child); len--; } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) { if (prevTextChild != null) { CharacterData ptc = (CharacterData) prevTextChild; ptc.setData(ptc.getNodeValue() + child.getNodeValue()); node.removeChild(child); len--; } else { prevTextChild = child; i++; } } else { prevTextChild = null; i++; } } } }
/** * Merges adjacent text/cdata nodes, so that there are no adjacent text/cdata nodes. Operates * recursively on the entire subtree. You thus lose information about any CDATA sections occurring * in the doc. * * @see #simplify */ public static void mergeAdjacentText(Node node) { Node child = node.getFirstChild(); while (child != null) { if (child instanceof Text || child instanceof CDATASection) { Node next = child.getNextSibling(); if (next instanceof Text || next instanceof CDATASection) { String fullText = child.getNodeValue() + next.getNodeValue(); ((CharacterData) child).setData(fullText); node.removeChild(next); } } else { mergeAdjacentText(child); } child = child.getNextSibling(); } }
/** * Remove a status monitor parameter based on the name attribute * * @param name * @throws XPathExpressionException */ public void removeStatParameters(String name) throws XPathExpressionException { Node statusMonitor = (Node) xpath.evaluate("/manifest/statusmonitor", document, XPathConstants.NODE); if (statusMonitor != null) { NodeList list = (NodeList) xpath.evaluate( "/manifest/statusmonitor/parameter[@name='" + name + "']", document, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); statusMonitor.removeChild(node); } } }
private void removeEvenNodes(Node node) { boolean toDelete = false; NodeList childNodesList = node.getChildNodes(); for (int i = 0; i < node.getChildNodes().getLength(); i++) { Node child = childNodesList.item(i); if (toDelete && child.getNodeType() == Node.ELEMENT_NODE) { node.removeChild(childNodesList.item(i)); toDelete = false; } else { if (child.getNodeType() == Node.ELEMENT_NODE) { toDelete = true; } } removeEvenNodes(childNodesList.item(i)); } }