List of usage examples for org.dom4j Element getQualifiedName
String getQualifiedName();
From source file:org.openflexo.docxparser.OpenXml2Html.java
License:Open Source License
private ParsedHtml getHtmlFromW_DrawingElement(Element element) { if (OpenXmlTag.getOpenXmlTag(element) != OpenXmlTag.w_drawing) { throw new InvalidElementException( "Cannot transform element to html, expecting element w:drawing and get '" + element.getQualifiedName() + "'"); }/*from ww w . j av a 2 s . com*/ ParsedHtml parsedHtml = new ParsedHtml(); try { Dom4jXPath xpath = new Dom4jXPath("descendant::a:blip"); xpath.addNamespace(DocxXmlUtil.NAMESPACE_DRAWINGMAIN.getPrefix(), DocxXmlUtil.NAMESPACE_DRAWINGMAIN.getURI()); Element ablipElement = (Element) xpath.selectSingleNode(element); if (ablipElement == null) { logger.warning("Cannot handle drawing tag: a:blip element not found"); return parsedHtml; } String imageRid = ablipElement.attributeValue(DocxQName.getQName(OpenXmlTag.r_embed)); if (imageRid == null) { logger.warning("Cannot handle drawing tag: r:embed attribute in a:blip element not found"); return parsedHtml; } PackageRelationship imageRelationship = documentPart.getRelationship(imageRid); if (imageRelationship == null) { logger.warning("Cannot handle drawing tag: imageRelationship with id '" + imageRid + "' not found"); return parsedHtml; } PackagePartName imagePartName = PackagingURIHelper.createPartName(imageRelationship.getTargetURI()); PackagePart imagePart = documentPart.getPackage().getPart(imagePartName); String imageFileName; if (imagePart != null) { byte[] imageBytes = DocxXmlUtil.getByteArrayFromInputStream(imagePart.getInputStream()); imageFileName = imagePartName.getName().substring(imagePartName.getName().lastIndexOf('/') + 1); parsedHtml.addNeededResource(new ParsedHtmlResource(imageFileName, imageBytes)); } else { imageFileName = ""; } Integer imageWidth = null; Integer imageHeight = null; Element extentElement = (Element) element.selectSingleNode("wp:inline/wp:extent"); if (extentElement != null) { String imageCx = extentElement.attributeValue("cx"); String imageCy = extentElement.attributeValue("cy"); if (imageCx != null) { imageWidth = getEnglishMetricUnitInPixel(imageCx); } if (imageCy != null) { imageHeight = getEnglishMetricUnitInPixel(imageCy); } } parsedHtml.appendHtml("<img src=\"" + resourcesDirectory + imageFileName + "\""); if (imageWidth != null) { parsedHtml.appendHtml(" width=\"" + imageWidth + "\""); } if (imageHeight != null) { parsedHtml.appendHtml(" height=\"" + imageHeight + "\""); } parsedHtml.appendHtml(" />"); return parsedHtml; } catch (InvalidFormatException e) { logger.log(Level.WARNING, "Cannot handle drawing tag: InvalidFormatException catched", e); return new ParsedHtml(); } catch (IOException e) { logger.log(Level.WARNING, "Cannot handle drawing tag: IOException catched", e); return new ParsedHtml(); } catch (JaxenException e) { logger.log(Level.WARNING, "Cannot handle drawing tag: JaxenException catched", e); return new ParsedHtml(); } }
From source file:org.openflexo.docxparser.OpenXml2Html.java
License:Open Source License
private ParsedHtml getHtmlFromW_TElement(Element element) throws InvalidElementException { if (OpenXmlTag.getOpenXmlTag(element) != OpenXmlTag.w_t) { throw new InvalidElementException("Cannot transform element to html, expecting element w:t and get '" + element.getQualifiedName() + "'"); }// w ww . j a v a 2s . co m ParsedHtml parsedHtml = new ParsedHtml(); parsedHtml.appendHtml(StringEscapeUtils.escapeHtml(element.getText())); return parsedHtml; }
From source file:org.openflexo.docxparser.OpenXmlTag.java
License:Open Source License
public static OpenXmlTag getOpenXmlTag(Element element) { try {//from w ww . ja va2 s . c o m return OpenXmlTag.valueOf(element.getQualifiedName().replaceAll(":", "_")); } catch (IllegalArgumentException e) { return OTHER; } }
From source file:org.orbeon.oxf.processor.tamino.dom4j.TDOM4JXMLOutputter.java
License:Open Source License
/** * <p>//ww w . jav a 2 s .c om * This will handle printing out an <code>{@link Element}</code>, * its <code>{@link Attribute}</code>s, and its value. * </p> * * @param element <code>Element</code> to output. * @param out <code>Writer</code> to write to. * @param indent <code>int</code> level of indention. * @param namespaces <code>List</code> stack of Namespaces in scope. */ protected void printElement(Element element, Writer out, int indentLevel, TDOM4JNamespaceStack namespaces) throws IOException { List mixedContent = element.elements(); boolean empty = mixedContent.size() == 0; boolean stringOnly = !empty && mixedContent.size() == 1 && mixedContent.get(0) instanceof String; // Print beginning element tag /* maybe the doctype, xml declaration, and processing instructions should only break before and not after; then this check is unnecessary, or maybe the println should only come after and never before. Then the output always ends with a newline */ indent(out, indentLevel); // Print the beginning of the tag plus attributes and any // necessary namespace declarations out.write("<"); out.write(element.getQualifiedName()); int previouslyDeclaredNamespaces = namespaces.size(); Namespace ns = element.getNamespace(); // Add namespace decl only if it's not the XML namespace and it's // not the NO_NAMESPACE with the prefix "" not yet mapped // (we do output xmlns="" if the "" prefix was already used and we // need to reclaim it for the NO_NAMESPACE) if (ns != Namespace.XML_NAMESPACE && !(ns == Namespace.NO_NAMESPACE && namespaces.getURI("") == null)) { String prefix = ns.getPrefix(); String uri = namespaces.getURI(prefix); if (!ns.getURI().equals(uri)) { // output a new namespace decl namespaces.push(ns); printNamespace(ns, out); } } // Print out additional namespace declarations List additionalNamespaces = element.additionalNamespaces(); if (additionalNamespaces != null) { for (int i = 0; i < additionalNamespaces.size(); i++) { Namespace additional = (Namespace) additionalNamespaces.get(i); String prefix = additional.getPrefix(); String uri = namespaces.getURI(prefix); if (!additional.getURI().equals(uri)) { namespaces.push(additional); printNamespace(additional, out); } } } printAttributes(element.attributes(), element, out, namespaces); // handle "" string same as empty if (stringOnly) { String elementText = trimText ? element.getTextTrim() : element.getText(); if (elementText == null || elementText.equals("")) { empty = true; } } if (empty) { // Simply close up if (!expandEmptyElements) { out.write(" />"); } else { out.write("></"); out.write(element.getQualifiedName()); out.write(">"); } maybePrintln(out); } else { // we know it's not null or empty from above out.write(">"); if (stringOnly) { // if string only, print content on same line as tags printElementContent(element, out, indentLevel, namespaces, mixedContent); } else { maybePrintln(out); printElementContent(element, out, indentLevel, namespaces, mixedContent); indent(out, indentLevel); } out.write("</"); out.write(element.getQualifiedName()); out.write(">"); maybePrintln(out); } // remove declared namespaces from stack while (namespaces.size() > previouslyDeclaredNamespaces) { namespaces.pop(); } }
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// ww w.ja v a2s. 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.XFormsModelSchemaValidator.java
License:Open Source License
private boolean validateElement(final Element element, final Acceptor acceptor, final IDConstraintChecker icc, final boolean isReportErrors) { boolean isElementValid = true; // Create StartTagInfo final StartTagInfo startTagInfo; {//w w w . j a va2s . co m final String uri = element.getNamespaceURI(); final String name = element.getName(); final String qName = element.getQualifiedName(); final List attributesList = element.attributes(); final AttributesImpl attributes = new AttributesImpl(); for (Object anAttributesList : attributesList) { final Attribute attribute = (Attribute) anAttributesList; final String attributeURI = attribute.getNamespaceURI(); final String attributeName = attribute.getName(); final String attributeQName = attribute.getQualifiedName(); final String attributeValue = attribute.getValue(); attributes.addAttribute(attributeURI, attributeName, attributeQName, null, attributeValue); } validationContext.setCurrentElement(element); startTagInfo = new StartTagInfo(uri, name, qName, attributes, validationContext); } final StringRef stringRef = new StringRef(); // Get child acceptor final Acceptor childAcceptor; { Acceptor tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, null); if (tempChildAcceptor == null) { if (isReportErrors) { tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, stringRef); addSchemaError(element, stringRef.str); isElementValid = false; } else { return false; } } childAcceptor = tempChildAcceptor; } // Handle id errors if (icc != null && isReportErrors) { icc.onNextAcceptorReady(startTagInfo, childAcceptor, element); isElementValid &= handleIDErrors(icc); } // Validate children final DatatypeRef datatypeRef = new DatatypeRef(); final boolean childrenValid = validateChildren(element, childAcceptor, startTagInfo, icc, datatypeRef, isReportErrors); if (!childrenValid) { if (isReportErrors) isElementValid = false; else return false; } // TODO: MSV doesn't allow getting the type if validity check fails. However, we would like to obtain datatype validity in XForms. if (!childAcceptor.isAcceptState(null)) { if (isReportErrors) { childAcceptor.isAcceptState(stringRef); addSchemaError(element, stringRef.str); isElementValid = false; } else { return false; } } else { // Attempt to set datatype name setDataType(datatypeRef, element); } // Handle id errors if (icc != null && isReportErrors) { icc.endElement(element, datatypeRef.types); isElementValid &= handleIDErrors(icc); } // Get back to parent acceptor if (!acceptor.stepForward(childAcceptor, null)) { if (isReportErrors) { acceptor.stepForward(childAcceptor, stringRef); addSchemaError(element, stringRef.str); isElementValid = false; } else { return false; } } if (isReportErrors) { // Element may be invalid or not return isElementValid; } else { // This element is valid return true; } }
From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java
License:Open Source License
public static String elementToDebugString(Element element) { // Open start tag final StringBuilder sb = new StringBuilder("<"); sb.append(element.getQualifiedName()); // Attributes if any for (Iterator i = element.attributeIterator(); i.hasNext();) { final Attribute currentAttribute = (Attribute) i.next(); sb.append(' '); sb.append(currentAttribute.getQualifiedName()); sb.append("=\""); sb.append(currentAttribute.getValue()); sb.append('\"'); }// w w w. j a v a2s. c om final boolean isEmptyElement = element.elements().isEmpty() && element.getText().length() == 0; if (isEmptyElement) { // Close empty element sb.append("/>"); } else { // Close start tag sb.append('>'); sb.append("[...]"); // Close element with end tag sb.append("</"); sb.append(element.getQualifiedName()); sb.append('>'); } return sb.toString(); }
From source file:org.sapia.util.xml.confix.Dom4jProcessor.java
License:Open Source License
private Object process(Object aParent, Element anElement, String setterName) throws ProcessingException { String aName = anElement.getName(); if (setterName == null) { setterName = aName;/*from ww w . jav a 2s .c o m*/ } CreationStatus status = null; try { status = getObjectFactory().newObjectFor(anElement.getNamespace().getPrefix(), anElement.getNamespace().getURI(), aName, aParent); } catch (ObjectCreationException oce) { if (aParent == null) { String aMessage = "Unable to create an object for the element " + anElement; throw new ProcessingException(aMessage, oce); } List children; if ((aParent != null) && (containsMethod("set", aParent, aName) || containsMethod("add", aParent, aName)) && ((children = anElement.elements()).size() == 1)) { Element child = (Element) children.get(0); process(aParent, child, setterName); return aParent; } try { String aValue = anElement.getTextTrim(); invokeSetter(aParent.getClass().getName(), aParent, aName, aValue); return aParent; } catch (ConfigurationException ce) { String aMessage = "Unable to create an object nor to call a setter for the element " + anElement; oce.printStackTrace(); throw new ProcessingException(aMessage, ce); } } String text = anElement.getTextTrim(); if (text.length() > 0) { try { invokeSetter(aName, status.getCreated(), "Text", text); } catch (ConfigurationException ce) { String aMessage = "The object '" + aName + "' does not accept free text"; throw new ProcessingException(aMessage, ce); } } try { // Process the attributes of the DOM element for (Iterator it = anElement.attributeIterator(); it.hasNext();) { Attribute attr = (Attribute) it.next(); invokeSetter(aName, status.getCreated(), attr.getName(), attr.getValue()); } // Process the child elements for (Iterator it = anElement.elementIterator(); it.hasNext();) { Element child = (Element) it.next(); if (status.getCreated() instanceof Dom4jHandlerIF) { ((Dom4jHandlerIF) status.getCreated()).handleElement(child); } else if (status.getCreated() instanceof XMLConsumer) { XMLConsumer cons = (XMLConsumer) status.getCreated(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLWriter writer; try { writer = new XMLWriter(bos, OutputFormat.createPrettyPrint()); } catch (UnsupportedEncodingException e) { throw new ProcessingException("Could not instantiate XMLWriter", e); } try { Element copy = child.createCopy(); copy.setDocument(null); writer.write(DocumentHelper.createDocument(copy)); ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray()); InputSource is = new InputSource(in); cons.consume(is); } catch (Exception e) { throw new ProcessingException("Could not pipe content of element: " + child.getQualifiedName() + " to XMLConsumer", e); } } else { process(status.getCreated(), child); } } // before assigning to parent, check if object // implements ObjectCreationCallback. if (status.getCreated() instanceof ObjectCreationCallback) { status._created = ((ObjectCreationCallback) status.getCreated()).onCreate(); } // assign obj to parent through setXXX or addXXX if ((aParent != null) && !status.wasAssigned() && !(status.getCreated() instanceof NullObject)) { assignToParent(aParent, status.getCreated(), setterName); } if (status.getCreated() instanceof NullObject) { return null; } return status.getCreated(); } catch (ConfigurationException ce) { String aMessage = "Unable to process the content of the element " + aName; throw new ProcessingException(aMessage, ce); } }
From source file:org.talend.mdm.ext.publish.util.SchemaProcessor.java
License:Open Source License
public static String transform2types(String infoXML) { String transformedXml = null; try {//from w w w.ja va 2 s. c om Document doc = DocumentHelper.parseText(infoXML); // first level only @SuppressWarnings("unchecked") List<Element> elements = doc.getRootElement().elements(); for (Iterator<Element> iterator = elements.iterator(); iterator.hasNext();) { Element element = (Element) iterator.next(); // remove concept element if (element.getQualifiedName().equals(elementID)) { Element parentElement = element.getParent(); if (parentElement != null) parentElement.remove(element); } } transformedXml = doc.asXML(); } catch (DocumentException e) { LOGGER.error(e.getLocalizedMessage(), e); return null; } catch (Exception e) { LOGGER.error(e.getLocalizedMessage(), e); return null; } return transformedXml; }
From source file:org.xwiki.store.serialization.xml.internal.XMLWriter.java
License:Open Source License
/** * Writes the closing tag of an {@link Element}. * <p>/* w ww .ja v a 2 s .c o m*/ * Compared to the DOM4J implementation, this function ensure closing of all opened * element including the one that is requested to be closed. Also writes a newline and * indents the closing element if required and if the last thing written was not a string. * </p> * * @param element <code>{@link Element}</code> to output. * @throws IOException a problem occurs during writing. * @see org.dom4j.io.XMLWriter#writeClose(org.dom4j.Element) */ @Override public void writeClose(final Element element) throws IOException { while (!this.parent.peek().getQualifiedName().equals(element.getQualifiedName())) { this.writeClose(this.parent.peek()); } super.setIndentLevel(this.parent.size() - 1); if (this.lcWriter.getLastChar() == CLOSE_ANGLE_BRACKET) { super.writePrintln(); super.indent(); } super.writeClose(this.parent.pop()); }