List of usage examples for org.w3c.dom Node getParentNode
public Node getParentNode();
From source file:openblocks.yacodeblocks.BlockSaveFileTest.java
private String describeNode(Node node) { if (node instanceof Element) { return "<" + node.getNodeName() + "> element"; } else if (node instanceof Attr) { return node.getNodeName() + " attribute of the " + describeNode(((Attr) node).getOwnerElement()); } else if (node instanceof Text) { return describeNode(node.getParentNode()); }//from w w w . j ava 2 s .co m throw new IllegalArgumentException( "node must an Element, an Attr, or a Text: " + node.getClass().getName()); }
From source file:org.adl.validator.sequence.SequenceValidator.java
/** * This method is called to initiate the validation process. * This method will trigger the parsing activity done by the * <code>ADLSCORMValidator</code>. Next, the DOM will be used to validate * the remaining checks required for full SCORM Validation. * * @param iRootNode Root sequence element. * * @return - Boolean value indicating the outcome of the validation checks. *//*w w w .j a v a 2 s. c o m*/ public boolean validate(Node iRootNode) { boolean validateResult = true; String msgText; String nodeName = iRootNode.getLocalName(); log.debug("validate()"); log.debug(" iRootNodeName coming in is " + nodeName); mRulesValidator.readInRules("sequence"); // check the parent and make sure it is in the right place String parentNodeName = iRootNode.getParentNode().getLocalName(); if (nodeName.equals("sequencingCollection")) { if (!parentNodeName.equals("manifest")) { msgText = Messages.getString("SequenceValidator.8", "sequencingCollection", "manifest"); log.debug("FAILED: " + msgText); DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.FAILED, msgText)); validateResult = false; } } // check the <sequencing> element and its children validateResult = compareToRules(iRootNode, "") && validateResult; // continuation of the application profile check, must validate that the // referencedObjective attribute references an objective //attribute (primary / objective) validateResult = checkReferencedObjectives() && validateResult; log.debug("validate()"); return validateResult; }
From source file:org.alfresco.repo.dictionary.CustomModelServiceImpl.java
/** * Finds the {@code module} element within the Share persisted-extension * XML file and then writes the XML fragment as the content of a newly created node. * * @param modelName the model name//from ww w .j a va 2s . co m * @return the created nodeRef */ protected NodeRef createCustomModelShareExtModuleRef(final String modelName) { final String moduleId = "CMM_" + modelName; final NodeRef formNodeRef = getShareExtModule(); ContentReader reader = contentService.getReader(formNodeRef, ContentModel.PROP_CONTENT); if (reader == null) { throw new CustomModelException("cmm.service.download.share_ext_node_read_err"); } InputStream in = reader.getContentInputStream(); Node moduleIdXmlNode = null; try { Document document = XMLUtil.parse(in); // the stream will be closed final String xpathQuery = "/extension//modules//module//id[.= '" + moduleId + "']"; XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile(xpathQuery); moduleIdXmlNode = (Node) expression.evaluate(document, XPathConstants.NODE); } catch (Exception ex) { throw new CustomModelException("cmm.service.download.share_ext_file_parse_err", ex); } if (moduleIdXmlNode == null) { throw new CustomModelException("cmm.service.download.share_ext_module_not_found", new Object[] { moduleId }); } final File moduleFile = TempFileProvider.createTempFile(moduleId, ".xml"); try { XMLUtil.print(moduleIdXmlNode.getParentNode(), moduleFile); } catch (IOException error) { throw new CustomModelException("cmm.service.download.share_ext_write_err", new Object[] { moduleId }, error); } return doInTransaction(MSG_DOWNLOAD_CREATE_SHARE_EXT_ERR, true, new RetryingTransactionCallback<NodeRef>() { @Override public NodeRef execute() throws Exception { final NodeRef nodeRef = createDownloadTypeNode(moduleId + SHARE_EXT_MODULE_SUFFIX); ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true); writer.setMimetype(MimetypeMap.MIMETYPE_XML); writer.setEncoding("UTF-8"); writer.putContent(moduleFile); return nodeRef; } }); }
From source file:org.alfresco.util.XMLUtil.java
/** * FOR DIAGNOSTIC PURPOSES ONLY - incomplete<br/> * Builds a path to the node relative to the to node provided. * @param from the node from which to build the xpath * @param to an ancestor of <tt>from</tt> which will be the root of the path * @return an xpath to <tt>to</tt> rooted at <tt>from</tt>. *///from w w w. j a v a 2 s . c om public static String buildXPath(final Node from, final Element to) { String result = ""; Node tmp = from; do { if (tmp instanceof Attr) { assert result.length() == 0; result = "@" + tmp.getNodeName(); } else if (tmp instanceof Element) { Node tmp2 = tmp; int position = 1; while (tmp2.getPreviousSibling() != null) { if (tmp2.getNodeName().equals(tmp.getNodeName())) { position++; } tmp2 = tmp2.getPreviousSibling(); } String part = tmp.getNodeName() + "[" + position + "]"; result = "/" + part + result; } else if (tmp instanceof Text) { assert result.length() == 0; result = "/text()"; } else { if (LOGGER.isDebugEnabled()) { throw new IllegalArgumentException("unsupported node type " + tmp); } } tmp = tmp.getParentNode(); } while (tmp != to.getParentNode() && tmp != null); return result; }
From source file:org.alfresco.web.bean.wcm.CreateFormWizard.java
/** * @return the possible root element names for use with the schema based on * the element declarations it defines.//from w w w . j av a 2 s . com */ public List<SelectItem> getSchemaRootElementNameChoices() { List<SelectItem> result = Collections.EMPTY_LIST; if (this.schema != null) { if (this.schemaRootElementNameChoices == null) { this.schemaRootElementNameChoices = new LinkedList<SelectItem>(); NodeList elements = this.schema.getElementsByTagNameNS(NamespaceConstants.XMLSCHEMA_NS, "element"); for (int i = 0; i < elements.getLength(); i++) { Node current = elements.item(i); if (current.getParentNode().equals(this.schema.getDocumentElement())) { this.schemaRootElementNameChoices .add(new SelectItem(current.getAttributes().getNamedItem("name").getNodeValue(), current.getAttributes().getNamedItem("name").getNodeValue())); } } } result = this.schemaRootElementNameChoices; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("getSchemaRootElementNameChoices(" + this.schema + ") = " + result.size()); } return result; }
From source file:org.ambraproject.rhino.content.xml.AbstractXpathReader.java
private static List<String> getParentChain(Node node) { Deque<String> stack = new ArrayDeque<>(); while (node != null) { stack.push(node.getNodeName());/*from ww w. ja v a2s.c o m*/ node = node.getParentNode(); } return ImmutableList.copyOf(stack); }
From source file:org.apache.axis.utils.XMLUtils.java
/** * Searches for the namespace URI of the given prefix in the given DOM range. * * The namespace is not searched in parent of the "stopNode". This is * usefull to get all the needed namespaces when you need to ouput only a * subtree of a DOM document.//from w w w. j av a2 s . c om * * @param prefix the prefix to find * @param e the starting node * @param stopNode null to search in all the document or a parent node where the search must stop. * @return null if no namespace is found, or the namespace URI. */ public static String getNamespace(String prefix, Node e, Node stopNode) { while (e != null && (e.getNodeType() == Node.ELEMENT_NODE)) { Attr attr = null; if (prefix == null) { attr = ((Element) e).getAttributeNode("xmlns"); } else { attr = ((Element) e).getAttributeNodeNS(Constants.NS_URI_XMLNS, prefix); } if (attr != null) return attr.getValue(); if (e == stopNode) return null; e = e.getParentNode(); } return null; }
From source file:org.apache.camel.maven.DocumentationEnricher.java
private int getNodeDepth(Node item) { int depth = 1; while (item.getParentNode() != null) { depth++;//from ww w . j ava2 s.c om item = item.getParentNode(); } return depth; }
From source file:org.apache.cocoon.util.jxpath.DOMFactory.java
public String getNamespaceURI(Element element, String prefix) { Node tmp = element; String nsAttr = prefix == null ? "xmlns" : "xmlns:" + prefix; while (tmp != null && tmp.getNodeType() == Node.ELEMENT_NODE) { element = (Element) tmp;//www .j a v a2s . c o m // First test element prefixes if (prefix == null) { if (element.getPrefix() == null) { return element.getNamespaceURI(); } } else if (prefix.equals(element.getPrefix())) { return element.getNamespaceURI(); } // Note: stupid DOM api returns "" when an attribute doesn't exist, so we use the Attr node. Attr nsAttrNode = ((Element) tmp).getAttributeNode(nsAttr); if (nsAttrNode != null) { return nsAttrNode.getValue(); } tmp = tmp.getParentNode(); } return null; }
From source file:org.apache.cocoon.xml.dom.DOMUtil.java
/** * Get a document fragment from a <code>Reader</code>. * The reader must provide valid XML, but it is allowed that the XML * has more than one root node. This xml is parsed by the * specified parser instance and a DOM DocumentFragment is created. *///from w w w . ja v a 2 s . co m public static DocumentFragment getDocumentFragment(SAXParser parser, Reader stream) throws ProcessingException { DocumentFragment frag = null; Writer writer; Reader reader; boolean removeRoot = true; try { // create a writer, // write the root element, then the input from the // reader writer = new StringWriter(); writer.write(XML_ROOT_DEFINITION); char[] cbuf = new char[16384]; int len; do { len = stream.read(cbuf, 0, 16384); if (len != -1) { writer.write(cbuf, 0, len); } } while (len != -1); writer.write("</root>"); // now test if xml input start with <?xml String xml = writer.toString(); String searchString = XML_ROOT_DEFINITION + "<?xml "; if (xml.startsWith(searchString) == true) { // now remove the surrounding root element xml = xml.substring(XML_ROOT_DEFINITION.length(), xml.length() - 7); removeRoot = false; } reader = new StringReader(xml); InputSource input = new InputSource(reader); DOMBuilder builder = new DOMBuilder(); builder.startDocument(); builder.startElement("", "root", "root", XMLUtils.EMPTY_ATTRIBUTES); IncludeXMLConsumer filter = new IncludeXMLConsumer(builder, builder); parser.parse(input, filter); builder.endElement("", "root", "root"); builder.endDocument(); // Create Document Fragment, remove <root> final Document doc = builder.getDocument(); frag = doc.createDocumentFragment(); final Node root = doc.getDocumentElement().getFirstChild(); root.normalize(); if (removeRoot == false) { root.getParentNode().removeChild(root); frag.appendChild(root); } else { Node child; while (root.hasChildNodes() == true) { child = root.getFirstChild(); root.removeChild(child); frag.appendChild(child); } } } catch (SAXException sax) { throw new ProcessingException("SAXException: " + sax, sax); } catch (IOException ioe) { throw new ProcessingException("IOException: " + ioe, ioe); } return frag; }