List of usage examples for org.w3c.dom Node removeChild
public Node removeChild(Node oldChild) throws DOMException;
oldChild
from the list of children, and returns it. From source file:org.nuxeo.common.xmap.DOMHelper.java
/** * Parses a string containing XML and returns a DocumentFragment containing * the nodes of the parsed XML./*from w ww . ja v a2 s . c om*/ */ 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 (ParserConfigurationException e) { log.error(e, e); } catch (SAXException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } }
From source file:org.odk.collect.android.logic.FormRelationsManager.java
/** * Removes a node identified by xpath from a document (instance). * * @param xpathStr The xpath for the node to remove. * @param document The document to mutate. * @return Returns true if and only if a node is removed. * @throws XPathExpressionException Another possible error that should * abort this routine./*from w ww. ja v a 2 s.co m*/ * @throws FormRelationsException Thrown if the xpath data for the * supplied document is bad. */ private static boolean removeFromDocument(String xpathStr, Document document) throws XPathExpressionException, FormRelationsException { boolean isModified = false; if (null != xpathStr) { // extract nodes using xpath XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression; expression = xpath.compile(xpathStr); Node node = (Node) expression.evaluate(document, XPathConstants.NODE); if (null == node) { throw new FormRelationsException(BAD_XPATH_INSTANCE, xpathStr); } if (LOCAL_LOG) { Log.i(TAG, "removeFromDocument -- attempting to delete: " + xpathStr); } Node removeNode = node.getParentNode(); removeNode.removeChild(node); isModified = true; } return isModified; }
From source file:org.ojbc.bundles.adapters.staticmock.AbstractStaticMockTest.java
protected Element removeElement(Document d, String xPath) throws Exception { Node n = XmlUtils.xPathNodeSearch(d, xPath); Node parent = n.getParentNode(); parent.removeChild(n); return (Element) parent; }
From source file:org.ojbc.bundles.adapters.staticmock.StaticMockQuery.java
private Document createFirearmRegistrationDocument(Document document, String firearmId) throws Exception { Document copy = createNewDocument(); copy.appendChild(copy.importNode(document.getDocumentElement(), true)); Node rootElement = XmlUtils.xPathNodeSearch(copy, "/*"); LOG.debug("Keeper: " + firearmId); NodeList otherFirearmNodes = XmlUtils.xPathNodeListSearch(rootElement, "firearm-ext:Firearm[@s:id != '" + firearmId + "']"); for (int i = 0; i < otherFirearmNodes.getLength(); i++) { Node goner = otherFirearmNodes.item(i); LOG.debug("Goner: " + XmlUtils.xPathStringSearch(goner, "@s:id")); rootElement.removeChild(goner); }//from ww w . ja v a 2 s . c o m NodeList otherItemRegNodes = XmlUtils.xPathNodeListSearch(rootElement, "firearm-ext:ItemRegistration[@s:id != /firearm-doc:PersonFirearmRegistrationQueryResults/nc:PropertyRegistrationAssociation[nc:ItemReference/@s:ref='" + firearmId + "']/nc:ItemRegistrationReference/@s:ref]"); for (int i = 0; i < otherItemRegNodes.getLength(); i++) { rootElement.removeChild(otherItemRegNodes.item(i)); } NodeList otherRegAssociationNodes = XmlUtils.xPathNodeListSearch(rootElement, "nc:PropertyRegistrationAssociation[nc:ItemReference/@s:ref != '" + firearmId + "']"); for (int i = 0; i < otherRegAssociationNodes.getLength(); i++) { rootElement.removeChild(otherRegAssociationNodes.item(i)); } copy.renameNode(rootElement, rootElement.getNamespaceURI(), "FirearmRegistrationQueryResults"); Node documentRootElement = XmlUtils.xPathNodeSearch(document, "/*"); rootElement.setPrefix(documentRootElement.getPrefix()); return copy; }
From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.ConsentCreatorService.java
/** * Removes the rule with the given ID from the PolicySet * // ww w.j a va 2 s . c o m * @param id * @param policySet * @return */ public boolean removeRule(String id, Document policySet) { NodeList rules = policySet.getElementsByTagName("Rule"); for (int i = 0; i < rules.getLength(); i++) { NamedNodeMap map = rules.item(i).getAttributes(); String val = map.getNamedItem("RuleId").getNodeValue(); if (val.equalsIgnoreCase(id)) { Node parent = rules.item(i).getParentNode(); parent.removeChild(rules.item(i)); i = rules.getLength(); return true; } } return false; }
From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java
/** * Updates the Target Element of the given Policy * // w w w . j a v a2s .c om * @param policy */ private void updatePolicyTargets(Node policy) { Node target = policy.getChildNodes().item(1); while (target.hasChildNodes()) { target.removeChild(target.getFirstChild()); } Vector<Node> resourceListFromRules = new Vector<Node>(); for (int i = 0; i < policy.getChildNodes().getLength(); i++) { Node n = policy.getChildNodes().item(i); if (n.getNodeName().equalsIgnoreCase("Rule")) { resourceListFromRules.add(n); } } Vector<Node> resourceListFromTarget = new Vector<Node>(); for (int i = 0; i < resourceListFromRules.size(); i++) { Node n = resourceListFromRules.elementAt(i); boolean matches = false; for (int k = 0; k < resourceListFromTarget.size(); k++) { if (n.getChildNodes().item(3).getChildNodes().item(3).getChildNodes().item(1).getChildNodes() .item(1).getChildNodes().item(1).getTextContent() .equalsIgnoreCase(resourceListFromTarget.elementAt(k).getChildNodes().item(3) .getChildNodes().item(3).getChildNodes().item(1).getChildNodes().item(1) .getChildNodes().item(1).getTextContent())) { matches = true; } } if (!matches) { resourceListFromTarget.add(n.cloneNode(true)); } } Document ress = null; try { ress = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new java.io.StringReader("<Resources></Resources>"))); } catch (Exception e) { Logger.getLogger(this.getClass()).error(e); } if (resourceListFromTarget.size() != 0) { Node copy = target.getOwnerDocument().importNode(ress.getDocumentElement(), true); target.appendChild(copy); for (int f = 0; f < resourceListFromTarget.size(); f++) { Node res = policy.getOwnerDocument().importNode(resourceListFromTarget.elementAt(f).getChildNodes() .item(3).getChildNodes().item(3).getChildNodes().item(1), true); copy.appendChild(res); } } }
From source file:org.openengsb.openengsbplugin.tools.Tools.java
/** * Remove node with given {@code xpath} from {@code targetDocument}. When {@code removeParent} is set to * {@code true} the parent node will also be removed if the removed node was the only child. The method returns * {@code true} if the node specified by {@code xpath} has been found and successfully removed from its parent node. *//* ww w . ja v a 2s . c o m*/ public static boolean removeNode(String xpath, Document targetDocument, NamespaceContext nsContext, boolean removeParent) throws XPathExpressionException { Node nodeToRemove = evaluateXPath(xpath, targetDocument, nsContext, XPathConstants.NODE, Node.class); if (nodeToRemove == null) { return false; } Node parent = nodeToRemove.getParentNode(); if (parent == null) { return false; } parent.removeChild(nodeToRemove); if (removeParent && parent.getChildNodes().getLength() == 0) { Node parentParent = parent.getParentNode(); if (parentParent != null) { parentParent.removeChild(parent); } } return true; }
From source file:org.openestate.io.core.XmlUtils.java
/** * Recursively remove any comments and unnecessary white spaces from a * {@link Node} and its children./*w ww. j a va2 s. c om*/ * * @param node * the node to clean */ public static void clean(Node node) { NodeList childNodes = node.getChildNodes(); for (int n = childNodes.getLength() - 1; n >= 0; n--) { Node child = childNodes.item(n); short nodeType = child.getNodeType(); if (nodeType == Node.ELEMENT_NODE) { XmlUtils.clean(child); } else if (nodeType == Node.COMMENT_NODE) { node.removeChild(child); } else if (nodeType == Node.TEXT_NODE) { String value = StringUtils.trimToNull(child.getNodeValue()); if (value == null) node.removeChild(child); else child.setNodeValue(value); } } }
From source file:org.openmrs.maven.plugins.distrotools.mojo.ValidateFormsMojo.java
/** * Applies macros in the given form XML (if there are any) * @param xml the form XML//from w ww . j a v a 2 s . c o m * @param documentBuilder the DOM document builder * @param documentTransformer the DOM document transformer * @return the form XML with macros applied */ protected static String applyMacros(String xml, DocumentBuilder documentBuilder, Transformer documentTransformer) throws IOException, TransformerException, SAXException { Document form = XmlUtils.stringToDocument(xml, documentBuilder); Node htmlformNode = XmlUtils.findFirstChild(form, "htmlform"); Node macrosNode = XmlUtils.findFirstChild(htmlformNode, "macros"); // If there are no macros defined, we just return the original document if (macrosNode == null) { return xml; } // Parse macros Properties macros = new Properties(); String macrosText = macrosNode.getTextContent(); if (macrosText != null) { macros.load(new ByteArrayInputStream(macrosText.getBytes())); } // Remove the macros node htmlformNode.removeChild(macrosNode); // Switch back to string so we can use string utilities to substitute xml = XmlUtils.documentToString(form, documentTransformer); // substitute any macros we found for (Object temp : macros.keySet()) { String key = (String) temp; String value = macros.getProperty(key, ""); xml = xml.replace("$" + key, value); } return xml; }
From source file:org.openmrs.module.clinicalsummary.rule.post.AdultReminderStudyRule.java
/** * @see org.openmrs.logic.Rule#eval(org.openmrs.logic.LogicContext, Integer, java.util.Map) *//*w w w. ja v a2 s . co m*/ @Override protected Result evaluate(final LogicContext context, final Integer patientId, final Map<String, Object> parameters) { String artifact = decodeArtifact(parameters.get(POST_EVALUATION_ARTIFACT)); Result result = new Result(artifact); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(artifact)); Document document = db.parse(is); Element element = document.getDocumentElement(); NodeList nodeList = element.getElementsByTagName("reminder"); if (nodeList != null && nodeList.getLength() > MAXIMUM_REMINDER_DISPLAYED) { Random random = new Random(); while (nodeList.getLength() > MAXIMUM_REMINDER_DISPLAYED) { Integer randomizedValue = random.nextInt(MAXIMUM_RANDOM_VALUE); Integer moduloValue = randomizedValue % nodeList.getLength(); // get the element Element nodeElement = (Element) nodeList.item(moduloValue); // get the parent node and then remove the above node Node parentNode = nodeElement.getParentNode(); parentNode.removeChild(nodeElement); } } OutputFormat format = new OutputFormat(); format.setIndenting(true); format.setLineWidth(150); Writer writer = new StringWriter(); XMLSerializer xmlSerializer = new XMLSerializer(writer, format); xmlSerializer.serialize(document); result = new Result(writer.toString()); } catch (Exception e) { log.error("Failed parsing xml string ...", e); } return result; }