List of usage examples for org.dom4j Node setText
void setText(String text);
Sets the text data of this node or this method will throw an UnsupportedOperationException
if it is read-only.
From source file:org.opencms.setup.xml.CmsSetupXmlHelper.java
License:Open Source License
/** * Sets the given value in all nodes identified by the given xpath of the given xml file.<p> * /*from w ww . j a v a 2s. c o m*/ * If value is <code>null</code>, all nodes identified by the given xpath will be deleted.<p> * * If the node identified by the given xpath does not exists, the missing nodes will be created * (if <code>value</code> not <code>null</code>).<p> * * @param document the xml document * @param xPath the xpath to set * @param value the value to set (can be <code>null</code> for deletion) * @param nodeToInsert optional, if given it will be inserted after xPath with the given value * * @return the number of successful changed or deleted nodes */ public static int setValue(Document document, String xPath, String value, String nodeToInsert) { int changes = 0; // be naive and try to find the node Iterator<Node> itNodes = CmsCollectionsGenericWrapper.<Node>list(document.selectNodes(xPath)).iterator(); // if not found if (!itNodes.hasNext()) { if (value == null) { // if no node found for deletion return 0; } // find the node creating missing nodes in the way Iterator<String> it = CmsStringUtil.splitAsList(xPath, "/", false).iterator(); Node currentNode = document; while (it.hasNext()) { String nodeName = it.next(); // if a string condition contains '/' while ((nodeName.indexOf("='") > 0) && (nodeName.indexOf("']") < 0)) { nodeName += "/" + it.next(); } Node node = currentNode.selectSingleNode(nodeName); if (node != null) { // node found currentNode = node; if (!it.hasNext()) { currentNode.setText(value); } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element elem = (Element) currentNode; if (!nodeName.startsWith("@")) { elem = handleNode(elem, nodeName); if (!it.hasNext() && CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) { elem.setText(value); } } else { // if node is attribute create it with given value elem.addAttribute(nodeName.substring(1), value); } currentNode = elem; } else { // should never happen if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.ERR_XML_SET_VALUE_2, xPath, value)); } break; } } if (nodeToInsert == null) { // if not inserting we are done return 1; } // if inserting, we just created the insertion point, so continue itNodes = CmsCollectionsGenericWrapper.<Node>list(document.selectNodes(xPath)).iterator(); } // if found while (itNodes.hasNext()) { Node node = itNodes.next(); if (nodeToInsert == null) { // if not inserting if (value != null) { // if found, change the value node.setText(value); } else { // if node for deletion is found node.getParent().remove(node); } } else { // first create the node to insert Element parent = node.getParent(); Element elem = handleNode(parent, nodeToInsert); if (value != null) { elem.setText(value); } // get the parent element list List<Node> list = CmsCollectionsGenericWrapper.<Node>list(parent.content()); // remove the just created element list.remove(list.size() - 1); // insert it back to the right position int pos = list.indexOf(node); list.add(pos + 1, elem); // insert after } changes++; } return changes; }
From source file:org.opencms.setup.xml.v8.CmsXmlUpdateFlexcache.java
License:Open Source License
/** * @see org.opencms.setup.xml.A_CmsSetupXmlUpdate#executeUpdate(org.dom4j.Document, java.lang.String, boolean) *//*w ww . jav a2 s. co m*/ @Override protected boolean executeUpdate(Document document, String xpath, boolean forReal) { Node node = document.selectSingleNode(xpath); if (node != null) { int pos = getXPathsToUpdate().indexOf(xpath); node.setText(m_capacities[pos]); return true; } return false; }
From source file:org.opencms.util.ant.CmsSetupXmlHelper.java
License:Open Source License
/** * Sets the given value in all nodes identified by the given xpath of the given xml file.<p> * /*from w w w . ja va 2s . c om*/ * If value is <code>null</code>, all nodes identified by the given xpath will be deleted.<p> * * If the node identified by the given xpath does not exists, the missing nodes will be created * (if <code>value</code> not <code>null</code>).<p> * * @param document the xml document * @param xPath the xpath to set * @param value the value to set (can be <code>null</code> for deletion) * @param nodeToInsert optional, if given it will be inserted after xPath with the given value * * @return the number of successful changed or deleted nodes */ @SuppressWarnings("unchecked") public static int setValue(Document document, String xPath, String value, String nodeToInsert) { int changes = 0; // be naive and try to find the node Iterator<Node> itNodes = document.selectNodes(xPath).iterator(); // if not found if (!itNodes.hasNext()) { if (value == null) { // if no node found for deletion return 0; } // find the node creating missing nodes in the way Iterator<String> it = CmsStringUtil.splitAsList(xPath, "/", false).iterator(); Node currentNode = document; while (it.hasNext()) { String nodeName = it.next(); // if a string condition contains '/' while ((nodeName.indexOf("='") > 0) && (nodeName.indexOf("']") < 0)) { nodeName += "/" + it.next(); } Node node = currentNode.selectSingleNode(nodeName); if (node != null) { // node found currentNode = node; if (!it.hasNext()) { currentNode.setText(value); } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element elem = (Element) currentNode; if (!nodeName.startsWith("@")) { elem = handleNode(elem, nodeName); if (!it.hasNext() && !CmsStringUtil.isEmptyOrWhitespaceOnly(value)) { elem.setText(value); } } else { // if node is attribute create it with given value elem.addAttribute(nodeName.substring(1), value); } currentNode = elem; } else { // should never happen break; } } if (nodeToInsert == null) { // if not inserting we are done return 1; } // if inserting, we just created the insertion point, so continue itNodes = document.selectNodes(xPath).iterator(); } // if found while (itNodes.hasNext()) { Node node = itNodes.next(); if (nodeToInsert == null) { // if not inserting if (value != null) { // if found, change the value node.setText(value); } else { // if node for deletion is found node.getParent().remove(node); } } else { // first create the node to insert Element parent = node.getParent(); Element elem = handleNode(parent, nodeToInsert); if (value != null) { elem.setText(value); } // get the parent element list List<Node> list = parent.content(); // remove the just created element list.remove(list.size() - 1); // insert it back to the right position int pos = list.indexOf(node); list.add(pos + 1, elem); // insert after } changes++; } return changes; }
From source file:org.orbeon.oxf.xforms.xbl.XBLTransformer.java
License:Open Source License
/** * Apply an XBL transformation, i.e. apply xbl:content, xbl:attr, etc. * * NOTE: This mutates shadowTreeDocument. */// ww w . j av a 2 s.co m public static Document transform(final Document shadowTreeDocument, final Element boundElement, final boolean excludeNestedHandlers, final boolean excludeNestedLHHA) { final DocumentWrapper documentWrapper = new DocumentWrapper(boundElement.getDocument(), null, XPathCache.getGlobalConfiguration()); Dom4jUtils.visitSubtree(shadowTreeDocument.getRootElement(), new Dom4jUtils.VisitorListener() { boolean isNestedHandler(Element e) { return e.getParent() == boundElement && EventHandlerImpl.isEventHandler(e); } boolean isNestedLHHA(Element e) { return e.getParent() == boundElement && LHHA.isLHHA(e); } boolean mustFilterOut(Element e) { return excludeNestedHandlers && isNestedHandler(e) || excludeNestedLHHA && isNestedLHHA(e); } public void startElement(Element element) { // Handle xbl:content final boolean isXBLContent = element.getQName().equals(XBL_CONTENT_QNAME); final List<Node> resultingNodes; if (isXBLContent) { final String includesAttribute = element.attributeValue(XFormsConstants.INCLUDES_QNAME); final String scopeAttribute = element.attributeValue(XFormsConstants.XXBL_SCOPE_QNAME); final List<Node> contentToInsert; if (includesAttribute == null) { // All bound node content must be copied over (except nested handlers if requested) final List<Node> elementContent = Dom4jUtils.content(boundElement); final List<Node> clonedContent = new ArrayList<Node>(); for (final Node node : elementContent) { if (node instanceof Element) { final Element currentElement = (Element) node; if (!mustFilterOut(currentElement)) clonedContent.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement)); } else if (!(node instanceof Namespace)) { clonedContent.add(Dom4jUtils.createCopy(node)); } } contentToInsert = clonedContent; } else { // Apply CSS selector // Convert CSS to XPath final String xpathExpression = CSSParser.toXPath(includesAttribute); final NodeInfo boundElementInfo = documentWrapper.wrap(boundElement); // TODO: don't use getNamespaceContext() as this is already computed for the bound element final List<Object> elements = XPathCache.evaluate(boundElementInfo, xpathExpression, new NamespaceMapping(Dom4jUtils.getNamespaceContext(element)), null, null, null, null, null, null);// TODO: locationData if (elements.size() > 0) { // Clone all the resulting elements contentToInsert = new ArrayList<Node>(elements.size()); for (Object o : elements) { final NodeInfo currentNodeInfo = (NodeInfo) o; final Element currentElement = (Element) ((VirtualNode) currentNodeInfo) .getUnderlyingNode(); if (!mustFilterOut(currentElement)) contentToInsert.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement)); } } else { // Clone all the element's children if any // See: http://www.w3.org/TR/xbl/#the-content contentToInsert = new ArrayList<Node>(element.nodeCount()); for (Object o : element.elements()) { final Element currentElement = (Element) o; if (!mustFilterOut(currentElement)) contentToInsert.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement)); } } } // Insert content if any if (contentToInsert != null && contentToInsert.size() > 0) { final List<Node> parentContent = Dom4jUtils.content(element.getParent()); final int elementIndex = parentContent.indexOf(element); parentContent.addAll(elementIndex, contentToInsert); } // Remove <xbl:content> from shadow tree element.detach(); resultingNodes = contentToInsert; if (!StringUtils.isBlank(scopeAttribute)) { // If author specified scope attribute, use it setAttribute(resultingNodes, XFormsConstants.XXBL_SCOPE_QNAME, scopeAttribute, null); } else { // By default, set xxbl:scope="outer" on resulting elements setAttribute(resultingNodes, XFormsConstants.XXBL_SCOPE_QNAME, "outer", null); } } else { // Element is simply kept resultingNodes = Collections.singletonList((Node) element); } // Handle attribute forwarding final Attribute xblAttr = element.attribute(XBL_ATTR_QNAME); // standard xbl:attr (custom syntax) final Attribute xxblAttr = element.attribute(XXBL_ATTR_QNAME); // extension xxbl:attr (XPath expression) if (xblAttr != null) { // Detach attribute (not strictly necessary?) xblAttr.detach(); // Get attribute value final String xblAttrString = xblAttr.getValue(); final StringTokenizer st = new StringTokenizer(xblAttrString); while (st.hasMoreTokens()) { final String currentValue = st.nextToken(); final int equalIndex = currentValue.indexOf('='); if (equalIndex == -1) { // No a=b pair, just a single QName final QName valueQName = Dom4jUtils.extractTextValueQName(element, currentValue, true); if (!valueQName.getNamespaceURI().equals(XFormsConstants.XBL_NAMESPACE_URI)) { // This is not xbl:text, copy the attribute setAttribute(resultingNodes, valueQName, boundElement.attributeValue(valueQName), boundElement); } else { // This is xbl:text // "The xbl:text value cannot occur by itself in the list" } } else { // a=b pair final QName leftSideQName; { final String leftSide = currentValue.substring(0, equalIndex); leftSideQName = Dom4jUtils.extractTextValueQName(element, leftSide, true); } final QName rightSideQName; { final String rightSide = currentValue.substring(equalIndex + 1); rightSideQName = Dom4jUtils.extractTextValueQName(element, rightSide, true); } final boolean isLeftSideXBLText = leftSideQName.getNamespaceURI() .equals(XFormsConstants.XBL_NAMESPACE_URI); final boolean isRightSideXBLText = rightSideQName.getNamespaceURI() .equals(XFormsConstants.XBL_NAMESPACE_URI); final String rightSideValue; final Element namespaceElement; if (!isRightSideXBLText) { // Get attribute value rightSideValue = boundElement.attributeValue(rightSideQName); namespaceElement = boundElement; } else { // Get text value // "any text nodes (including CDATA nodes and whitespace text nodes) that are // explicit children of the bound element must have their data concatenated" rightSideValue = boundElement.getText();// must use getText() and not stringValue() namespaceElement = null; } if (rightSideValue != null) { // NOTE: XBL doesn't seem to says what should happen if the source attribute is not // found! We assume the rule is ignored in this case. if (!isLeftSideXBLText) { // Set attribute value setAttribute(resultingNodes, leftSideQName, rightSideValue, namespaceElement); } else { // Set text value // "value of the attribute on the right-hand side are to be represented as text // nodes underneath the shadow element" // TODO: "If the element has any child nodes in the DOM (any nodes, including // comment nodes, whitespace text nodes, or even empty CDATA nodes) then the pair // is in error and UAs must ignore it, meaning the attribute value is not forwarded" setText(resultingNodes, rightSideValue); } } } // TODO: handle xbl:lang? // TODO: handle type specifiers? } } else if (xxblAttr != null) { // Detach attribute (not strictly necessary?) xxblAttr.detach(); // Get attribute value final String xxblAttrString = xxblAttr.getValue(); final NodeInfo boundElementInfo = documentWrapper.wrap(boundElement); // TODO: don't use getNamespaceContext() as this is already computed for the bound element final List<Object> nodeInfos = XPathCache.evaluate(boundElementInfo, xxblAttrString, new NamespaceMapping(Dom4jUtils.getNamespaceContext(element)), null, null, null, null, null, null);// TODO: locationData if (nodeInfos.size() > 0) { for (Object nodeInfo : nodeInfos) { final NodeInfo currentNodeInfo = (NodeInfo) nodeInfo; if (currentNodeInfo.getNodeKind() == org.w3c.dom.Node.ATTRIBUTE_NODE) { // This is an attribute final Attribute currentAttribute = (Attribute) ((VirtualNode) currentNodeInfo) .getUnderlyingNode(); setAttribute(resultingNodes, currentAttribute.getQName(), currentAttribute.getValue(), currentAttribute.getParent()); } } } } // Prefix resulting xhtml:*/(@id |@for) // NOTE: We could also do the prefixing in the handlers, when the page is output. // // * Benefit of prefixing here: done statically // * Drawback of prefixing here: in the future if we try to reuse simple shadow trees this won't work // { // if (resultingNodes != null && resultingNodes.size() > 0) { // for (Iterator i = resultingNodes.iterator(); i.hasNext();) { // final Node node = (Node) i.next(); // if (node instanceof Element) { // Dom4jUtils.visitSubtree((Element) node, new Dom4jUtils.VisitorListener() { // public void startElement(Element element) { // if (XMLConstants.XHTML_NAMESPACE_URI.equals(element.getNamespaceURI())) { // // Found XHTML element // // // Update @id and @for if any // final Attribute idAttribute = element.attribute("id"); // if (idAttribute != null) { // idAttribute.setValue(prefix + idAttribute.getValue()); // } // final Attribute forAttribute = element.attribute("for"); // if (forAttribute != null) { // forAttribute.setValue(prefix + forAttribute.getValue()); // } // } // } // // public void endElement(Element element) { // } // // public void text(Text text) { // } // }); // } // } // } // } } private void setAttribute(List<Node> nodes, QName attributeQName, String attributeValue, Element namespaceElement) { if (nodes != null && nodes.size() > 0) { for (final Node node : nodes) { if (node instanceof Element) { final Element element = ((Element) node); // Copy missing namespaces, so that copying things like ref="foo:bar" work as expected Dom4jUtils.copyMissingNamespaces(namespaceElement, element); element.addAttribute(attributeQName, attributeValue); } } } } private void setText(List<Node> nodes, String value) { if (nodes != null && nodes.size() > 0) { for (final Node node : nodes) { if (node instanceof Element) { node.setText(value); } } } } public void endElement(Element element) { } public void text(Text text) { } }, true); return shadowTreeDocument; }
From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java
License:Open Source License
/** * Go over the Node and its children and make sure that there are no two contiguous text nodes so as to ensure that * XPath expressions run correctly. As per XPath 1.0 (http://www.w3.org/TR/xpath): * * "As much character data as possible is grouped into each text node: a text node never has an immediately * following or preceding sibling that is a text node." * * dom4j Text and CDATA nodes are combined together. * * @param nodeToNormalize Node hierarchy to normalize * @return the input node, normalized *//*from w ww . j a v a 2 s . co m*/ public static Node normalizeTextNodes(Node nodeToNormalize) { final List<Node> nodesToDetach = new ArrayList<Node>(); nodeToNormalize.accept(new VisitorSupport() { public void visit(Element element) { final List children = element.content(); Node previousNode = null; StringBuilder sb = null; for (Iterator i = children.iterator(); i.hasNext();) { final Node currentNode = (Node) i.next(); if (previousNode != null) { if (isTextOrCDATA(previousNode) && isTextOrCDATA(currentNode)) { final CharacterData previousNodeText = (CharacterData) previousNode; if (sb == null) sb = new StringBuilder(previousNodeText.getText()); sb.append(currentNode.getText()); nodesToDetach.add(currentNode); } else if (isTextOrCDATA(previousNode)) { // Update node if needed if (sb != null) { previousNode.setText(sb.toString()); } previousNode = currentNode; sb = null; } else { previousNode = currentNode; sb = null; } } else { previousNode = currentNode; sb = null; } } // Update node if needed if (previousNode != null && sb != null) { previousNode.setText(sb.toString()); } } }); // Detach nodes only in the end so as to not confuse the acceptor above for (final Node currentNode : nodesToDetach) { currentNode.detach(); } return nodeToNormalize; }
From source file:org.pdfsam.guiclient.utils.xml.XMLConfig.java
License:Open Source License
/** * Given a DOM object it sets the new tag value * * @param xpath/*ww w.ja v a 2 s . c o m*/ * @param value * new value of the xml tag */ public void setXMLConfigValue(String xpath, String value) throws Exception { Node node = document.selectSingleNode(xpath); if (node == null) { node = document.selectSingleNode(xpath.substring(0, xpath.lastIndexOf("/"))); if (node != null) { node = (Node) ((Element) node).addElement(xpath.substring(xpath.lastIndexOf("/") + 1)); } } if (node != null) { node.setText(value); } else { log.warn("Unable to set " + value + " to " + xpath); } }
From source file:org.pentaho.actionsequence.dom.ActionSequenceDocument.java
License:Open Source License
/** * Sets the action sequence result type//w w w. j ava 2s . c o m * * @param value * the result type */ public void setResultType(String value) { Element actSeq = (Element) document.selectSingleNode(ACTION_SEQUENCE); if (value == null) { Node subElement = actSeq.selectSingleNode(ACTION_SEQUENCE_DOCUMENTATION_RESULT_TYPE); if (subElement != null) { subElement.detach(); fireHeaderChanged(this); } } else { Element subElement = DocumentHelper.makeElement(actSeq, ACTION_SEQUENCE_DOCUMENTATION_RESULT_TYPE); subElement.setText(value == null ? "" : value); //$NON-NLS-1$ fireHeaderChanged(this); } }
From source file:org.pentaho.jpivot.AnalysisSaver.java
License:Open Source License
/** * @param document//from w ww .j a v a2 s. c om * @param props * @return */ private static Document updateDocument(final Document document, final HashMap props) { try { Element componentDefinition = null; Element actionOutput = null; Element actionSequenceOutput = null; Node actionSequence = document.selectSingleNode("/action-sequence"); //$NON-NLS-1$ if (actionSequence == null) { throw new InvalidDocumentException( Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0004_INVALID_ORIGIN_DOCUMENT")); //$NON-NLS-1$ } Element asElement = ((Element) actionSequence); Node title = null; String propertyTitle = (String) props.get(AnalysisSaver.TITLE_NODE_NAME); title = asElement.selectSingleNode(AnalysisSaver.TITLE_NODE_NAME); if ((title == null) && (propertyTitle != null)) { title = asElement.addElement(AnalysisSaver.TITLE_NODE_NAME); } if ((title != null) && (propertyTitle != null)) { // remove existing text if it's there title.setText(""); //$NON-NLS-1$ ((Element) title).addCDATA(propertyTitle); // adds CDATA } // Next, we need to retrieve the PivotViewComponent action and // process/update it.. there could possibly be more than one // PivotViewComponent in an action sequence, however, we have no idea // how to figure out which one to process, so we default to picking the last one we found. componentDefinition = (Element) document.selectSingleNode( "//action-definition[component-name='PivotViewComponent']/component-definition"); //$NON-NLS-1$ if (componentDefinition == null) { throw new InvalidDocumentException( Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0005_INVALID_NO_PIVOT_ACTION")); //$NON-NLS-1$ } AnalysisSaver.updateComponent(componentDefinition, props); // Get the action's root action-output node, in case we need to add the // appropriate outputs for the pivot view... actionOutput = (Element) document .selectSingleNode("//action-definition[component-name='PivotViewComponent']/action-outputs"); //$NON-NLS-1$ AnalysisSaver.updateOutput(actionOutput, props); // Get the action's root action sequence output node, in case we need to add the // appropriate outputs for the pivot view... actionSequenceOutput = (Element) document.selectSingleNode("//action-sequence/outputs"); //$NON-NLS-1$ AnalysisSaver.updateOutput(actionSequenceOutput, props); } catch (Exception e) { e.printStackTrace(); } return document; }
From source file:org.pentaho.jpivot.AnalysisSaver.java
License:Open Source License
/** * @param componentDefinition/*from www . j a v a2 s. c o m*/ * @param props */ private static void updateComponent(final Element componentDefinition, final HashMap props) { Iterator iter = props.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); Node node = componentDefinition.selectSingleNode(key.toString()); if (node == null) { node = componentDefinition.addElement(key.toString()); } if (PivotViewComponent.OPTIONS.equals(node.getName())) { List optionsList = (List) props.get(key); Iterator optsIter = optionsList.iterator(); while (optsIter.hasNext()) { String anOption = optsIter.next().toString(); Node anOptionNode = node.selectSingleNode(anOption); if (anOptionNode == null) { ((Element) node).addElement(anOption); } } } else { Object value = props.get(key); if (value != null) { // remove existing text node.setText(""); //$NON-NLS-1$ ((Element) node).addCDATA(value.toString()); } } } // the property "mdx" is no longer being put in the hashmap. So, // query will be passed properly now. }
From source file:org.pentaho.pac.server.config.WebXml.java
License:Open Source License
public boolean setServletMapping(String name, String value) { String xPath = MessageFormat.format(SERVLET_NAME_TEMPLATE_XPATH, name); Node node = document.selectSingleNode(xPath); if (node != null) { node = node.selectSingleNode("../jsp-file"); //$NON-NLS-1$ }/*from ww w. j a v a 2 s . c om*/ if (node != null) { node.setText(value); return true; } return false; }