List of usage examples for org.dom4j Element content
List<Node> content();
From source file:org.orbeon.oxf.transformer.xupdate.statement.Append.java
License:Open Source License
private void insert(Object parentNode, URIResolver uriResolver, Object context, VariableContextImpl variableContext, DocumentContext documentContext) { if (parentNode instanceof Document) { if (((Document) parentNode).getRootElement() != null) throw new ValidationException("Document already has a root element", getLocationData()); Utils.insert(getLocationData(), (Document) parentNode, 0, Utils.execute(uriResolver, context, variableContext, documentContext, statements)); } else if (parentNode instanceof Element) { Element parentElement = (Element) parentNode; List children = parentElement.content(); int position = child == null ? parentElement.content().size() : parentElement.content().size() == 0 ? 0 : ((Number) ((Node) children.get(0)).createXPath(child).evaluate(children)).intValue(); Utils.insert(getLocationData(), parentElement, position, Utils.execute(uriResolver, context, variableContext, documentContext, statements)); } else {//from w w w .j a v a 2s . c o m throw new ValidationException("Cannot append in a: " + parentNode.getClass().getName(), getLocationData()); } }
From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java
License:Open Source License
/** * Evaluate a sequence a statements, and insert the result of the * evaluation the given parent node at the given position. */// w w w . j a va2 s . c o m public static void insert(LocationData locationData, Node parent, int position, Object toInsert) { List nodesToInsert = xpathObjectToDOM4JList(locationData, toInsert); if (parent instanceof Element) Collections.reverse(nodesToInsert); for (Iterator j = nodesToInsert.iterator(); j.hasNext();) { Object object = j.next(); Node node = object instanceof String || object instanceof Number ? Dom4jUtils.createText(object.toString()) : (Node) ((Node) object).clone(); if (parent instanceof Element) { Element element = (Element) parent; if (node instanceof Attribute) { element.attributes().add(node); } else { element.content().add(position, node); } } else if (parent instanceof Attribute) { Attribute attribute = (Attribute) parent; attribute.setValue(attribute.getValue() + node.getText()); } else if (parent instanceof Document) { // Update a document element final Document document = (Document) parent; if (node instanceof Element) { if (document.getRootElement() != null) throw new ValidationException("Document already has a root element", locationData); document.setRootElement((Element) node); } else if (node instanceof ProcessingInstruction) { document.add(node); } else { throw new ValidationException( "Only an element or processing instruction can be at the root of a document", locationData); } } else { throw new ValidationException("Cannot insert into a node of type '" + parent.getClass() + "'", locationData); } } }
From source file:org.orbeon.oxf.transformer.xupdate.TemplatesHandlerImpl.java
License:Open Source License
private Statement[] parseStatements(List nodes) { List statements = new ArrayList(); for (Iterator i = nodes.iterator(); i.hasNext();) { Node node = (Node) i.next(); if (node.getNodeType() == Node.TEXT_NODE) { if (!"".equals(node.getText().trim())) statements.add(new Text(node.getText().trim())); } else if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; NamespaceContext namespaceContext = new SimpleNamespaceContext( Dom4jUtils.getNamespaceContext(element)); if (XUpdateConstants.XUPDATE_NAMESPACE_URI.equals(element.getNamespaceURI())) { if (element.getName().equals("remove")) { statements.add(new Remove((LocationData) element.getData(), element.attributeValue("select"), namespaceContext)); } else if (element.getName().equals("update")) { statements//from ww w. ja v a2 s . c o m .add(new Update((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("append")) { statements.add(new Append((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, element.attributeValue("child"), parseStatements(element.content()))); } else if (element.getName().equals("insert-before")) { statements.add( new InsertBefore((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("insert-after")) { statements.add( new InsertAfter((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("for-each")) { statements .add(new ForEach((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("while")) { statements.add(new While((LocationData) element.getData(), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("value-of")) { statements.add(new ValueOf((LocationData) element.getData(), element.attributeValue("select"), namespaceContext)); } else if (element.getName().equals("copy-of")) { statements.add(new CopyOf((LocationData) element.getData(), element.attributeValue("select"), namespaceContext)); } else if (element.getName().equals("node-set")) { statements.add(new NodeSet((LocationData) element.getData(), element.attributeValue("select"), namespaceContext)); } else if (element.getName().equals("attribute")) { statements.add(new Attribute((LocationData) element.getData(), parseQName(element), parseStatements(element.content()))); } else if (element.getName().equals("namespace")) { statements.add(new Namespace((LocationData) element.getData(), element.attributeValue("name"), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("element")) { statements.add(new DynamicElement((LocationData) element.getData(), parseQName(element), parseStatements(element.content()))); } else if (element.getName().equals("if")) { statements.add(new If((LocationData) element.getData(), element.attributeValue("test"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("choose")) { List whenTests = new ArrayList(); List whenNamespaceContext = new ArrayList(); List whenStatements = new ArrayList(); for (Iterator j = element.elements("when").iterator(); j.hasNext();) { Element whenElement = (Element) j.next(); whenTests.add(whenElement.attributeValue("test")); whenNamespaceContext .add(new SimpleNamespaceContext(Dom4jUtils.getNamespaceContext(whenElement))); whenStatements.add(parseStatements(whenElement.content())); } Element otherwiseElement = element.element("otherwise"); statements.add(new Choose((LocationData) element.getData(), (String[]) whenTests.toArray(new String[whenTests.size()]), (NamespaceContext[]) whenNamespaceContext .toArray(new NamespaceContext[whenNamespaceContext.size()]), (Statement[][]) whenStatements.toArray(new Statement[whenStatements.size()][]), otherwiseElement == null ? null : parseStatements(otherwiseElement.content()))); } else if (element.getName().equals("variable")) { statements.add(new Variable((LocationData) element.getData(), parseQName(element), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("assign")) { statements.add(new Assign((LocationData) element.getData(), parseQName(element), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("function")) { statements.add(new Function((LocationData) element.getData(), parseQName(element), parseStatements(element.content()))); } else if (element.getName().equals("param")) { statements.add(new Param((LocationData) element.getData(), parseQName(element), element.attributeValue("select"), namespaceContext, parseStatements(element.content()))); } else if (element.getName().equals("message")) { statements.add( new Message((LocationData) element.getData(), parseStatements(element.content()))); } else if (element.getName().equals("error")) { statements.add( new Error((LocationData) element.getData(), parseStatements(element.content()))); } else { throw new ValidationException( "Unsupported XUpdate element '" + element.getQualifiedName() + "'", (LocationData) element.getData()); } } else { Element staticElement = new NonLazyUserDataElement(element.getQName()); List childNodes = new ArrayList(); for (Iterator j = element.attributes().iterator(); j.hasNext();) staticElement.add((org.dom4j.Attribute) ((org.dom4j.Attribute) j.next()).clone()); for (Iterator j = element.content().iterator(); j.hasNext();) { Node child = (Node) j.next(); if (child instanceof org.dom4j.Namespace) { staticElement.add((Node) child.clone()); } else { childNodes.add(child); } } statements.add(new StaticElement((LocationData) element.getData(), staticElement, parseStatements(childNodes))); } } else if (node.getNodeType() == Node.NAMESPACE_NODE) { // Ignore namespace declarations } else { throw new OXFException("Unsupported node: " + node.getNodeTypeName()); } } return (Statement[]) statements.toArray(new Statement[statements.size()]); }
From source file:org.orbeon.oxf.xforms.action.actions.XFormsDeleteAction.java
License:Open Source License
private static DeleteInfo doDeleteOne(IndentedLogger indentedLogger, List collectionToUpdate, int deleteIndex) { final NodeInfo nodeInfoToRemove = (NodeInfo) collectionToUpdate.get(deleteIndex - 1); final NodeInfo parentNodeInfo = nodeInfoToRemove.getParent(); final Node nodeToRemove = XFormsUtils.getNodeFromNodeInfo(nodeInfoToRemove, CANNOT_DELETE_READONLY_MESSAGE); final List contentToUpdate; final int indexInContentToUpdate; final Element parentElement = nodeToRemove.getParent(); if (parentElement != null) { // Regular case if (nodeToRemove instanceof Attribute) { contentToUpdate = parentElement.attributes(); } else {/* ww w . j a v a 2 s. co m*/ contentToUpdate = parentElement.content(); } indexInContentToUpdate = contentToUpdate.indexOf(nodeToRemove); } else if (nodeToRemove.getDocument() != null && nodeToRemove == nodeToRemove.getDocument().getRootElement()) { // Case of root element where parent is Document contentToUpdate = nodeToRemove.getDocument().content(); indexInContentToUpdate = contentToUpdate.indexOf(nodeToRemove); } else if (nodeToRemove instanceof Document) { // Case where node to remove is Document // "except if the node is the root document element of an instance then the delete action // is terminated with no effect." if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("xf:delete", "ignoring attempt to delete document node"); return null; } else { // Node to remove doesn't have a parent so we can't delete it // This can happen for nodes already detached, or nodes newly created with e.g. xf:element() return null; } // Actually perform the deletion // "The node at the delete location in the Node Set Binding node-set is deleted" contentToUpdate.remove(indexInContentToUpdate); return new DeleteInfo(parentNodeInfo, nodeInfoToRemove, indexInContentToUpdate); }
From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java
License:Open Source License
/** * Typed version of the dom4j API.//from w ww .ja va2 s . com */ @SuppressWarnings("unchecked") public static List<Node> content(Element container) { return (List<Node>) container.content(); }
From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java
License:Open Source License
/** * Removes the elements and text inside the given element, but not the attributes or namespace * declarations on the element./*from w w w . ja v a 2 s . c o m*/ */ public static void clearElementContent(final Element elt) { final java.util.List cntnt = elt.content(); for (final java.util.ListIterator j = cntnt.listIterator(); j.hasNext();) { final Node chld = (Node) j.next(); if (chld.getNodeType() == Node.TEXT_NODE || chld.getNodeType() == Node.ELEMENT_NODE) { j.remove(); } } }
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 www. 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.orbeon.oxf.xml.dom4j.NonLazyUserDataElement.java
License:Open Source License
/** * @return A clone. The clone will have parent == null but will have any necessary namespace * declarations this element's ancestors. *///from ww w. j av a 2s . co m public Object clone() { final NonLazyUserDataElement ret = cloneInternal(); org.dom4j.Element anstr = getParent(); done: if (anstr != null) { final NodeComparator nc = new NodeComparator(); final java.util.TreeSet nsSet = new java.util.TreeSet(nc); do { final java.util.List sibs = anstr.content(); for (final java.util.Iterator itr = sibs.iterator(); itr.hasNext();) { final org.dom4j.Node sib = (org.dom4j.Node) itr.next(); if (sib.getNodeType() != org.dom4j.Node.NAMESPACE_NODE) continue; nsSet.add(sib); } anstr = anstr.getParent(); } while (anstr != null); if (nsSet.isEmpty()) break done; for (final java.util.Iterator itr = nsSet.iterator(); itr.hasNext();) { final org.dom4j.Namespace ns = (org.dom4j.Namespace) itr.next(); final String pfx = ns.getPrefix(); if (ret.getNamespaceForPrefix(pfx) != null) continue; ret.add(ns); } } return ret; }
From source file:org.pentaho.ui.xul.impl.AbstractXulLoader.java
License:Open Source License
protected void processOverlay(Element overlayEle, Element srcEle) { for (Object child : overlayEle.elements()) { Element overlay = (Element) child; String overlayId = overlay.attributeValue("ID"); logger.debug("Processing overlay\nID: " + overlayId); Element sourceElement = srcEle.getDocument().elementByID(overlayId); if (sourceElement == null) { logger.error("Could not find corresponding element in src doc with id: " + overlayId); continue; }//from w w w. j a v a 2 s . c o m logger.debug("Found match in source doc:"); String removeElement = overlay.attributeValue("removeelement"); if (removeElement != null && removeElement.equalsIgnoreCase("true")) { sourceElement.getParent().remove(sourceElement); } else { List attribs = overlay.attributes(); // merge in attributes for (Object o : attribs) { Attribute atr = (Attribute) o; sourceElement.addAttribute(atr.getName(), atr.getValue()); } Document targetDocument = srcEle.getDocument(); // lets start out by just including everything for (Object overlayChild : overlay.elements()) { Element pluckedElement = (Element) overlay.content() .remove(overlay.content().indexOf(overlayChild)); if (pluckedElement.getName().equals("dialog")) { String newOnload = pluckedElement.attributeValue("onload"); if (newOnload != null) { String existingOnload = targetDocument.getRootElement().attributeValue("onload"); String finalOnload = ""; if (existingOnload != null) { finalOnload = existingOnload + ", "; } finalOnload += newOnload; targetDocument.getRootElement().setAttributeValue("onload", finalOnload); } } String insertBefore = pluckedElement.attributeValue("insertbefore"); String insertAfter = pluckedElement.attributeValue("insertafter"); String position = pluckedElement.attributeValue("position"); // determine position to place it int positionToInsert = -1; if (insertBefore != null) { Element insertBeforeTarget = sourceElement.elementByID(insertBefore); positionToInsert = sourceElement.elements().indexOf(insertBeforeTarget); } else if (insertAfter != null) { Element insertAfterTarget = sourceElement.elementByID(insertAfter); positionToInsert = sourceElement.elements().indexOf(insertAfterTarget); if (positionToInsert != -1) { positionToInsert++; // we want to be after that point; } } else if (position != null) { int pos = Integer.parseInt(position); positionToInsert = (pos <= sourceElement.elements().size()) ? pos : -1; } if (positionToInsert == -1) { // default to last positionToInsert = sourceElement.elements().size(); } if (positionToInsert > sourceElement.elements().size()) { sourceElement.elements().add(pluckedElement); } else { sourceElement.elements().add(positionToInsert, pluckedElement); } logger.debug("processed overlay child: " + ((Element) overlayChild).getName() + " : " + pluckedElement.getName()); } } } }
From source file:org.talend.mdm.webapp.browserecords.server.service.UploadService.java
License:Open Source License
protected void fillFieldValue(Element currentElement, String fieldPath, String fieldValue, Row row, String[] record) throws Exception { String parentPath = null;/* w w w . jav a 2 s . c o m*/ boolean isAttribute = false; List<String> valueList = null; List<Element> valueNodeList = new ArrayList<Element>(); if (fieldPath.endsWith(Constants.XSI_TYPE_QUALIFIED_NAME)) { isAttribute = true; String field[] = fieldPath.split(Constants.FILE_EXPORT_IMPORT_SEPARATOR); fieldPath = field[0]; } fieldValue = transferFieldValue(fieldPath, fieldValue, multipleValueSeparator); String[] xpathPartArray = fieldPath.split("/"); //$NON-NLS-1$ String xpath = xpathPartArray[0]; if (!isAttribute) { if (multipleValueSeparator != null && !multipleValueSeparator.isEmpty()) { valueList = splitString(fieldValue, "\\" + String.valueOf(multipleValueSeparator.charAt(0))); //$NON-NLS-1$ } } for (int i = 1; i < xpathPartArray.length; i++) { if (currentElement != null) { parentPath = xpath; xpath = xpath + "/" + xpathPartArray[i]; //$NON-NLS-1$ if (entityModel.getTypeModel(xpath).isMultiOccurrence() && multiNodeMap.get(xpath) == null) { List<Element> multiNodeList = new ArrayList<Element>(); if (valueList != null) { if (isPartialUpdate) { if (currentElement.element(xpathPartArray[i]) == null) { currentElement.addElement(xpathPartArray[i]); } List<Element> elementList = currentElement.elements(xpathPartArray[i]); for (Element e : elementList) { multiNodeList.add(e); } if (elementList.size() < valueList.size()) { for (int j = 1; j <= valueList.size() - elementList.size(); j++) { currentElement.addElement(xpathPartArray[i]); multiNodeList.add((Element) currentElement.content() .get(currentElement.content().size() - 1)); } } } else { for (int j = 0; j < valueList.size(); j++) { Element element = currentElement.element(xpathPartArray[i]); int index = currentElement.content().indexOf(element); if (index + j >= currentElement.content().size() || currentElement.content() .get(currentElement.content().indexOf(element) + j) != element) { Element createCopy = element.createCopy(); currentElement.content().add(createCopy); multiNodeList.add(createCopy); } else { multiNodeList.add(element); } } } } multiNodeMap.put(xpath, multiNodeList); if (multiNodeList.size() > 0) { currentElement = multiNodeList.get(multiNodeList.size() - 1); } } else if (multiNodeMap.get(parentPath) != null) { List<Element> parentlist = multiNodeMap.get(parentPath); for (int j = 0; j < parentlist.size(); j++) { Element parentElement = parentlist.get(j); Element element = parentElement.element(xpathPartArray[i]); if (element == null) { element = parentElement.addElement(xpathPartArray[i]); } valueNodeList.add(element); } if (valueNodeList.size() > 0) { currentElement = valueNodeList.get(valueNodeList.size() - 1); } } else { if (currentElement.element(xpathPartArray[i]) != null) { currentElement = currentElement.element(xpathPartArray[i]); } else { currentElement = currentElement.addElement(xpathPartArray[i]); } } if (i == xpathPartArray.length - 1) { if (isAttribute) { setAttributeValue(currentElement, fieldValue); } else { if (valueNodeList.size() > 0) { for (int j = 0; j < valueList.size(); j++) { setFieldValue(valueNodeList.get(j), valueList.get(j)); } } else if (multiNodeMap.get(xpath) != null) { List<Element> multiNodeList = multiNodeMap.get(xpath); for (int j = 0; j < valueList.size(); j++) { setFieldValue(multiNodeList.get(j), valueList.get(j)); } } else { setFieldValue(currentElement, fieldValue); } } } else { String currentElemntPath = currentElement.getPath().substring(1); if (inheritanceNodePathList != null && inheritanceNodePathList.contains(currentElemntPath)) { Integer xsiTypeIndex = xsiTypeMap .get(currentElemntPath + "/@" + Constants.XSI_TYPE_QUALIFIED_NAME); //$NON-NLS-1$ if (xsiTypeIndex != null) { String xsiTypeValue = ""; //$NON-NLS-1$ if (FILE_TYPE_EXCEL_SUFFIX.equals(fileType.toLowerCase()) || FILE_TYPE_EXCEL2010_SUFFIX.equals(fileType.toLowerCase())) { xsiTypeValue = row.getCell(xsiTypeIndex).getRichStringCellValue().getString(); } else if (FILE_TYPE_CSV_SUFFIX.equals(fileType.toLowerCase())) { xsiTypeValue = record[i]; } setAttributeValue(currentElement, xsiTypeValue); } else { throw new UploadException( MESSAGES.getMessage(new Locale(currentElemntPath), "missing_attribute", //$NON-NLS-1$ currentElemntPath + "/@" + Constants.XSI_TYPE_QUALIFIED_NAME)); //$NON-NLS-1$ } } } } } }