List of usage examples for org.w3c.dom Node getParentNode
public Node getParentNode();
From source file:org.kuali.test.utils.Utils.java
/** * * @param tm//from www . j av a 2 s. c o m * @param node * @return */ public static Element getMatchingParent(TagMatcher tm, Element node) { Element retval = null; Node parent = node.getParentNode(); int cnt = 0; int totalCnt = Integer.MAX_VALUE; boolean limited = false; String sdef = tm.getSearchDefinition(); if (StringUtils.isNotBlank(sdef)) { if (StringUtils.isNumeric(sdef)) { totalCnt = Integer.parseInt(sdef); limited = true; } } while ((cnt < totalCnt) && isElement(parent)) { if (parent.getNodeName().equalsIgnoreCase(tm.getTagName())) { cnt++; TagMatchAttribute[] attrs = null; if (tm.getMatchAttributes() != null) { attrs = tm.getMatchAttributes().getMatchAttributeArray(); } if ((!limited || (cnt == totalCnt)) && isTagMatch((Element) parent, tm)) { retval = (Element) parent; break; } } parent = parent.getParentNode(); } return retval; }
From source file:org.kuali.test.utils.Utils.java
/** * * @param doc/*w w w .ja v a 2 s. c om*/ * @param tagnames */ public static void removeTagsFromDocument(Document doc, String[] tagnames) { List<Node> removeList = new ArrayList<Node>(); for (String tag : tagnames) { // if this tag has a '.' in the name the attribute(s) are specified // in the form '<tagname>.<attname>=<attvalue>,<attname>=<attvalue>...' int pos = tag.indexOf("."); String tagname = tag; Map<String, String> attmap = null; if (pos > -1) { tagname = tag.substring(0, pos); attmap = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(tag.substring(pos + 1), ","); while (st.hasMoreTokens()) { String s = st.nextToken(); pos = s.indexOf("="); if (pos > -1) { attmap.put(s.substring(0, pos), s.substring(pos + 1)); } } } NodeList l = doc.getDocumentElement().getElementsByTagName(tagname); for (int i = 0; i < l.getLength(); ++i) { Element item = (Element) l.item(i); // if attribute is specified check the node for matching attribute if ((attmap != null) && !attmap.isEmpty()) { int cnt = 0; for (String key : attmap.keySet()) { String checkValue = attmap.get(key); String val = item.getAttribute(key); if (StringUtils.isNotBlank(val) && val.equals(checkValue)) { cnt++; } else { break; } } if (cnt == attmap.size()) { removeList.add(item); } } else { removeList.add(item); } } } for (Node node : removeList) { // this check required because we may have already removed the parent if (node.getParentNode() != null) { node.getParentNode().removeChild(node); } } }
From source file:org.metaeffekt.dcc.commons.ant.MergeXmlTask.java
protected void saveToFile(Document document, File outputFile) throws XPathExpressionException, TransformerException { XPath xPath = xPathfactory.newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); }//from w w w .j ava2s .co m DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(outputFile); transformer.transform(source, result); }
From source file:org.metaeffekt.dcc.commons.ant.MergeXmlTaskTest.java
/** * This strategy is used for mailet contribution in dcc-james-3 package ... therefore * the test is using this context.//from w w w . ja v a2 s . c o m * * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws XPathExpressionException */ @Test public void testMergeSuceedingSiblingStrategy() throws IOException, ParserConfigurationException, SAXException, XPathExpressionException { File targetDir = new File("target/merge-xml"); targetDir.mkdirs(); File outputFile = new File(targetDir, "mailetcontainer-out.xml"); MergeXmlTask mergeXmlTask = new MergeXmlTask(); mergeXmlTask.setProject(new Project()); File inputDir = new File("src/test/resources/merge-xml-test"); mergeXmlTask.setInputFile(new File(inputDir, "mailetcontainer.xml")); mergeXmlTask.setFragmentFile(new File(inputDir, "mailet-fragment.xml")); mergeXmlTask.setOutputFile(outputFile); mergeXmlTask.setSucceedingSiblingNode("//mailet[@class='LocalDelivery']"); String nodeToIntegrateXpathString = "//mailet[@class='org.metaeffekt.dcc.MailetToBeMerged']"; mergeXmlTask.setFragmentNodes(nodeToIntegrateXpathString); mergeXmlTask.execute(); Validate.isTrue(outputFile.exists()); Validate.isTrue(FileUtils.readFileToString(outputFile).contains("value42")); // ensure that it is merge to the correct position: BEGIN ----> Document createdDocument = createDocument(outputFile); NodeList nodes = getNodes(createdDocument, nodeToIntegrateXpathString); Validate.isTrue(1 == nodes.getLength()); Node mergedNode = nodes.item(0); Node expectedParent = getNodes(createdDocument, "//processor[@state='transport']").item(0); Validate.isTrue(mergedNode.getParentNode().equals(expectedParent)); Node expectedPredecessorElement = getNodes(createdDocument, "//mailet[@class='ToSenderFolder']").item(0); Validate.isTrue(getPreviousElementNode(mergedNode).equals(expectedPredecessorElement)); Node expectedSuccessor = getNodes(createdDocument, "//mailet[@class='LocalDelivery']").item(0); Validate.isTrue(getNextSibling(mergedNode).equals(expectedSuccessor)); // <---- ensure that it is merge to the correct position: END }
From source file:org.miradi.xml.TestXmpz2ForwardMigration.java
private Vector<ImmutablePair<Node, Node>> removeUUIDFields(Node node) { Vector<ImmutablePair<Node, Node>> nodesToRemove = new Vector<ImmutablePair<Node, Node>>(); if (node.getNodeName().endsWith(BaseObject.TAG_UUID)) { nodesToRemove.add(new ImmutablePair<>(node, node.getParentNode())); }// w ww .j a va 2s .c om NodeList childNodes = node.getChildNodes(); for (int index = 0; index < childNodes.getLength(); ++index) { Node childNode = childNodes.item(index); nodesToRemove.addAll(removeUUIDFields(childNode)); } return nodesToRemove; }
From source file:org.ms123.common.importing.XmlImporter.java
private String getElementPath(Element e) { StringBuilder sb = new StringBuilder(); sb.append(e.getNodeName());// w ww . j a v a2 s . co m Node n = e.getParentNode(); while (n != null) { String s = n.getNodeName(); if ("#document".equals(s)) { break; } sb.insert(0, s + "/"); n = n.getParentNode(); } String ret = sb.toString(); int slash = ret.indexOf("/"); if (slash != -1) { return ret.substring(slash + 1); } return ret; }
From source file:org.nuxeo.ecm.diff.service.impl.FieldDiffHelper.java
/** * Computes a field diff.//from www . j a v a 2 s. co m * <p> * First gets all needed elements to compute the field diff: * <ul> * <li>propertyHierarchy: list holding the property hierarchy * * <pre> * Every time we encounter a list, a complex or a content node going up in the DOM tree * from the property node to the prefixed field node, we add it to the property * hierarchy. * If it is a list item node, we set its index in the hierarchy. * If it is a complex item node, we set its name in the hierarchy. * If it is a content item node (ie. "encoding", "mime-type", "filename" or "digest"), * we set its name in the hierarchy. * * Example: complex list * * The "true" property's hierarchy is: * [{list,"0"},{complex, "complexBoolean"}] * * The "jack" property's hierarchy is: * [{list,"1"},{complex, "complexString"}] * * The "UTF-8" property's hierarchy is: * [{list,"0"},{complex, "complexString"},{content, "encoding"}] * * <list type="complexList"> * <complexItem type="complex"> * <complexString type="string">joe</complexString> * <complexBoolean type="boolean">true</complexBoolean> * <complexContent type="content"> * <encoding>UTF-8</encoding> * <mime-type>text/plain</mime-type> * <filename>My_file.txt</filename> * <digest>5dafdabf966043c8c8cef20011e939a2</digest> * </complexContent> * </complexItem> * <complexItem type="complex"> * <complexString type="string">jack</complexString> * <complexBoolean type="boolean">false</complexBoolean> * </complexItem> * </list> * </pre> * * </li> * </ul> * * @param docDiff the doc diff * @param controlNodeDetail the control node detail * @param testNodeDetail the test node detail * @param fieldDifferenceCount the field difference countadd * @param difference the difference * @return true if a field diff has been found * @throws ClientException the client exception */ public static boolean computeFieldDiff(DocumentDiff docDiff, NodeDetail controlNodeDetail, NodeDetail testNodeDetail, int fieldDifferenceCount, Difference difference) throws ClientException { // Use control node or if null test node to detect schema and // field elements Node currentNode = controlNodeDetail.getNode(); if (currentNode == null) { currentNode = testNodeDetail.getNode(); } if (currentNode != null) { String field = null; String currentNodeName = currentNode.getNodeName(); List<PropertyHierarchyNode> propertyHierarchy = new ArrayList<PropertyHierarchyNode>(); // Detect a schema element, // for instance: <schema name="dublincore" xmlns:dc="...">. // Otherwise build the property hierarchy. // For a content type property (blob) don't take into account a // difference on the "data" field, since what makes the difference // between 2 blobs is either the filename or the digest. Node parentNode = currentNode.getParentNode(); while (parentNode != null && !SCHEMA_ELEMENT.equals(currentNodeName) && !ExportConstants.BLOB_DATA.equals(parentNode.getNodeName())) { // Get property type String propertyType = getPropertyType(currentNode); String parentPropertyType = getPropertyType(parentNode); // Fill in property hierarchy if (PropertyType.isListType(parentPropertyType)) { int currentNodePosition = getNodePosition(currentNode); propertyHierarchy.add( new PropertyHierarchyNode(parentPropertyType, String.valueOf(currentNodePosition))); } else if (PropertyType.isComplexType(parentPropertyType) || PropertyType.isContentType(parentPropertyType)) { propertyHierarchy.add(new PropertyHierarchyNode(parentPropertyType, currentNodeName)); } // Detect a field element, ie. an element that has a // prefix, for instance: <dc:title>. if (SCHEMA_ELEMENT.equals(parentNode.getNodeName())) { String currentNodeLocalName = currentNode.getLocalName(); // TODO: manage better the facet case if (!FACET_ELEMENT.equals(currentNodeLocalName)) { field = currentNodeLocalName; if (PropertyType.isSimpleType(propertyType) || PropertyType.isListType(propertyType) && propertyHierarchy.isEmpty() || PropertyType.isComplexType(propertyType) && propertyHierarchy.isEmpty() || PropertyType.isContentType(propertyType) && propertyHierarchy.isEmpty()) { propertyHierarchy.add(new PropertyHierarchyNode(propertyType, null)); } } } currentNode = parentNode; currentNodeName = currentNode.getNodeName(); parentNode = parentNode.getParentNode(); } // If we found a schema element (ie. we did not // reached the root element, ie. parentNode != null) and a // nested field element, we can compute the diff for this // field. if (parentNode != null && field != null && !propertyHierarchy.isEmpty()) { String schema = currentNodeName; // Get schema name NamedNodeMap attr = currentNode.getAttributes(); if (attr != null && attr.getLength() > 0) { Node nameAttr = attr.getNamedItem(NAME_ATTRIBUTE); if (nameAttr != null) { schema = nameAttr.getNodeValue(); } } // Reverse property hierarchy Collections.reverse(propertyHierarchy); // Pretty log field difference LOGGER.debug(String.format( "Found field difference #%d on [%s]/[%s] with hierarchy %s: [%s (%s)] {%s --> %s}", fieldDifferenceCount + 1, schema, field, propertyHierarchy, difference.getDescription(), difference.getId(), controlNodeDetail.getValue(), testNodeDetail.getValue())); // Compute field diff computeFieldDiff(docDiff, schema, field, propertyHierarchy, difference.getId(), controlNodeDetail, testNodeDetail); // Return true since a field diff has been found return true; } else {// Non-field difference LOGGER.debug(String.format("Found non-field difference: [%s (%s)] {%s --> %s}", difference.getDescription(), difference.getId(), controlNodeDetail.getValue(), testNodeDetail.getValue())); } } return false; }
From source file:org.nuxeo.ecm.diff.service.impl.FieldDiffHelper.java
/** * Computes a TEXT_VALUE diff./* w ww.ja v a 2s .c om*/ * * @param fieldDiff the field diff * @param controlNodeDetail the control node detail * @param testNodeDetail the test node detail * @throws ClientException the client exception */ private static void computeTextValueDiff(PropertyDiff fieldDiff, NodeDetail controlNodeDetail, NodeDetail testNodeDetail) throws ClientException { String leftValue = controlNodeDetail.getValue(); String rightValue = testNodeDetail.getValue(); Node controlNode = controlNodeDetail.getNode(); if (controlNode == null) { throw new ClientException("Control node should never be null."); } Node controlParentNode = controlNode.getParentNode(); if (controlParentNode == null) { throw new ClientException("Control parent node should never be null."); } String controlParentNodePropertyType = getPropertyType(controlParentNode); String fieldDiffPropertyType = fieldDiff.getPropertyType(); // Simple type if (PropertyType.isSimpleType(fieldDiffPropertyType)) { ((SimplePropertyDiff) fieldDiff).setLeftValue(leftValue); ((SimplePropertyDiff) fieldDiff).setRightValue(rightValue); } // List type else if (PropertyType.isListType(fieldDiffPropertyType)) { ((ListPropertyDiff) fieldDiff).putDiff(getNodePosition(controlParentNode), new SimplePropertyDiff(controlParentNodePropertyType, leftValue, rightValue)); } // Complex type else if (PropertyType.isComplexType(fieldDiffPropertyType)) { ((ComplexPropertyDiff) fieldDiff).putDiff(controlParentNode.getNodeName(), new SimplePropertyDiff(controlParentNodePropertyType, leftValue, rightValue)); } // Content type else { ContentPropertyDiff contentPropertyDiff = ((ContentPropertyDiff) fieldDiff); setContentSubPropertyDiff(contentPropertyDiff, controlParentNode.getNodeName(), leftValue, rightValue); } }
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 www . j a v a 2 s. c o 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);/* w w w .j a va 2s . c om*/ return (Element) parent; }