/** * Returns the content of an element as string. The element itself * is ignored. * * @param e the element to get the content from * @return the content as string */ protected String getContent(Element e) throws IOException { XMLOutputter out = new XMLOutputter(); StringWriter writer = new StringWriter(); for (Content child : e.getContent()) { if (child instanceof Element) { out.output((Element) child, writer); } else if (child instanceof Text) { Text t = (Text) child; String trimmedText = t.getTextTrim(); if (!trimmedText.equals("")) { Text newText = new Text(trimmedText); out.output(newText, writer); } } } return writer.toString(); }
/** * * @param iterator * with hasNext() == true. Iterator position will change * @return the last node from the current group. i.e. the last <a> element from a consecutive group of <a> * elements * @author sholzer (Aug 25, 2015) */ private Content getLastNodeFromGroup(ListIterator<Content> iterator) { Content currentNode = iterator.next(); if (iterator.hasNext()) { Content nextNode = iterator.next(); if (nextNode.getClass().equals(currentNode.getClass())) { if (nextNode instanceof Element) { Element currentElement = (Element) currentNode; Element nextElement = (Element) nextNode; if (!nextElement.getName().equals(currentElement.getName())) { return currentNode; } } iterator.previous(); return getLastNodeFromGroup(iterator); } else { return currentNode; } } else { return currentNode; } }
/** * Peeks into the list provided by the iterator if an element with the tag ,,name'' exists. * @param name * the name to be looking for * @param iterator * list iterator of a list to be looked at. next() and previous() will be called multiple * times. Position of the iterator will be the same as before * @return true if an element with tag ,,name'' exists in the list of iterator * @author sholzer (Aug 25, 2015) */ private boolean peekFor(String name, ListIterator<Content> iterator) { if (iterator.hasNext()) { // take a step forwards Content currentNode = iterator.next(); boolean result; // if the current node is an element with the searched name return true if (currentNode instanceof Element && ((Element) currentNode).getName().equals(name)) { result = true; } else { // otherwise look at the next node result = peekFor(name, iterator); } // take a step backwards iterator.previous(); return result; } else {// at the end of the list obviously there was no such element return false; } }
@Test public void testList() throws Exception { Element child1 = new Element("child").setText("Hallo Welt"); Element child2 = new Element("child").setText("hello world"); Element child3 = new Element("child").setText("Bonjour le monde"); List<Content> l1 = new ArrayList<>(); l1.add(child1); l1.add(child2); l1.add(child3); Element root = new Element("root"); root.addContent(l1); String formattedXML = "<root>\n<child>Hallo Welt</child>\n" + "<child>hello world</child>" + "<child>Bonjour le monde</child>\n</root>"; SAXBuilder b = new SAXBuilder(); Document doc = b.build(new ByteArrayInputStream(formattedXML.getBytes(Charset.forName("UTF-8")))); assertEquals("Elements should be equal", true, MCRXMLHelper.deepEqual(root, doc.getRootElement())); }
@Override public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) throws JODTemplateException { final IteratorIterable<Element> atElements = document.getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace())); final List<Element> atElementsList = new ArrayList<>(); while (atElements.hasNext()) { atElementsList.add(atElements.next()); } for (Element at : atElementsList) { if (at.getContentSize() != 0) { final Content content = at.getContent(0); if (content instanceof Comment) { final Comment comment = (Comment) content; processComment(comment, at, slide, configuration); } } } return document; }
private void assertEquals(Element element1, Element element2) { Assert.assertEquals(element1.getName(), element2.getName()); Assert.assertEquals(this.getAttributes(element1), this.getAttributes(element2)); List<Content> children1 = element1.getContent(); List<Content> children2 = element2.getContent(); Assert.assertEquals(children1.size(), children2.size()); for (int i = 0; i < children1.size(); i++) { Content child1 = children1.get(0); Content child2 = children2.get(0); if (child1 instanceof Element) { this.assertEquals((Element) child1, (Element) child2); } else { Assert.assertEquals(child1.getValue(), child2.getValue()); } } }
private List<Content> getOriginalHeadContent(org.jdom2.Document doc) { org.jdom2.Element root = doc.getRootElement(); List<Content> contentList = new ArrayList<>(); if (root != null) { org.jdom2.Element headElement = root.getChild("head", Constants.NAMESPACE_XHTML); if (headElement != null) { List<Content> contents = headElement.getContent(); contentList.addAll(contents); } } //erst ausserhalb der Schleife detachen for (Content content : contentList) { content.detach(); } return contentList; }
/** * This method retrieves the element of a modified entry. the modified * entries' content is stored in a separated XML-Document (see * {@link #modifiedEntries modifiedEntries}. each element of this document * has a timestamp-attribute that equals the timestamp-attribute of an entry * in the {@link #desktop desktop}-Document. * <br><br> * So, by passing a {@code timestamp} value, this method searches whether we * have any modified entry that has the same timestamp-attribut, and if so, * it returns that element which was modified (and thus differs from an * entry's content as it is stored in the original database). * * @param timestamp the timestamp which should match the requested entry's * timestamp-attribute * @return the modified entry as element, or {@code null} if no entry was * found. */ private Element retrieveModifiedEntryElementFromTimestamp(String timestamp) { // retrieve all elements List<Content> elementList = modifiedEntries.getRootElement().getContent(); // when we have any content, go on... if (elementList.size() > 0) { for (Content elementList1 : elementList) { // retrieve each single element Element e = (Element) elementList1; // retrieve timestamp-attribute String att = e.getAttributeValue(ATTR_TIMESTAMP); // compare timestamp-attribute-value to timestamp-parameter if (att != null && att.equals(timestamp)) { // if they match, return that element return e; } } } // else return null return null; }
private List<Element> getChildren(Element parentElement, String tagName) { IteratorIterable<Content> iter = parentElement.getDescendants(); List<Element> children = new ArrayList<Element>(); while (iter.hasNext()) { Element elem; try { elem = (Element) iter.next(); } catch (ClassCastException e) { continue; } if (tagName.equalsIgnoreCase(elem.getName())) { children.add(elem); } } return children; }
private LinkedList<String> doFilter(String in, Set<String> xpaths) throws IOException { LinkedList<String> result = new LinkedList<String>(); try { Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(new StringReader(in)); XMLOutputter out = new XMLOutputter(); for (String xp : xpaths) { XPathExpression<Content> xpath = XPathFactory.instance().compile(xp, Filters.content()); for (Content node : xpath.evaluate(doc)) { if(node instanceof Element) { result.add(out.outputString((Element) node)); } else if(node instanceof Text) { result.add(out.outputString((Text) node)); } } } return result; } catch (JDOMException xpe) { throw new IllegalArgumentException("error while processing xpath expressions: '" + xpaths + "'", xpe); } }
private Content replaceVarsRecursive(TemplateNode node){ Content c = node.xmlNode.clone(); if( c instanceof Element ){ Element e = (Element) c; e.getContent().clear(); for( TemplateNode n : node.children ) { Content child = replaceVarsRecursive(n); e.addContent(child); } } if( node instanceof TemplateVarNode ){ TemplateVarNode tvn = (TemplateVarNode) node; replace(c, tvn.content); } return c; }
@Override public Object convert(ConvertContext cxt, Rule rule) throws ConvertException { String xpath = (String ) rule.getParams()[0]; logger.debug("xpath: {}",xpath); XPathExpression<Object> objs = factory.compile(xpath); List<Object> objList = objs.diagnose(cxt.getSourceDocument(), false).getResult(); logger.debug(">> {}",objList); if(objList==null){ return null; } for(Object obj :objList){ if(obj instanceof Element){ return ((Element) obj).getValue(); }else if(obj instanceof Content){ return ((Content) obj).getValue(); } } return "null"; }
@Override public Object convert(ConvertContext cxt, Rule rule) throws ConvertException { String slotName = (String ) rule.getParams()[0]; String xpath = "/SubmitSoapRequest/objective/slot[slotName='"+slotName+"']/slotValue/text()"; logger.trace("xpath: {}",xpath); XPathExpression<Object> objs = factory.compile(xpath); List<Object> objList = objs.diagnose(cxt.getSourceDocument(), false).getResult(); logger.trace(">> {}",objList); if(objList==null){ return null; } for(Object obj :objList){ if(obj instanceof Element){ return ((Element) obj).getValue(); }else if(obj instanceof Content){ return ((Content) obj).getValue(); } } return "XXXX"; }
@Override public Object convert(ConvertContext cxt, Rule rule) throws ConvertException { String groupName = (String ) rule.getParams()[0]; String itemName = (String ) rule.getParams()[1]; String xpath = "/CdpeRequest/phyExamInfo/examGroup[groupName='"+groupName+"']/groupItem[itemName='"+itemName+"']/itemValue/text()"; logger.debug("xpath: {}",xpath); XPathExpression<Object> objs = factory.compile(xpath); List<Object> objList = objs.diagnose(cxt.getSourceDocument(), false).getResult(); logger.trace(">> {}",objList); if(objList==null){ return null; } for(Object obj :objList){ if(obj instanceof Element){ return ((Element) obj).getValue(); }else if(obj instanceof Content){ return ((Content) obj).getValue(); } } return "XXXX"; }
private List<Content> readIncludedDocument(@Nullable Path basePath, Path includeFile, @Nullable Element includeElement) throws InvalidXMLException { final Path fullPath = findIncludeFile(basePath, includeFile, includeElement); if(fullPath == null) { throw new InvalidXMLException("Failed to find include: " + includeFile, includeElement); } return readIncludedDocument(fullPath, includeElement); }
private List<Content> readIncludedDocument(Path fullPath, @Nullable Element includeElement) throws InvalidXMLException { if(includeStack.contains(fullPath)) { throw new InvalidXMLException("Circular include: " + Joiner.on(" --> ").join(includeStack), includeElement); } includeStack.push(fullPath); try { return readDocument(fullPath).getRootElement().cloneContent(); } finally { includeStack.pop(); } }
private List<Content> processConditional(Element el, boolean invert) throws InvalidXMLException { for(Node attr : Node.fromAttrs(el)) { boolean expected = XMLUtils.parseBoolean(attr); boolean actual = getEnvironment(attr.getName(), Boolean.class, attr); if(expected != actual) { return invert ? el.cloneContent() : Collections.<Content>emptyList(); } } return invert ? Collections.<Content>emptyList() : el.cloneContent(); }
private void processChildren(Path file, Element parent) throws InvalidXMLException { for(int i = 0; i < parent.getContentSize(); i++) { Content content = parent.getContent(i); if(!(content instanceof Element)) continue; Element child = (Element) content; List<Content> replacement = null; switch(child.getName()) { case "include": replacement = processIncludeElement(file, child); break; case "if": replacement = processConditional(child, false); break; case "unless": replacement = processConditional(child, true); break; } if(replacement != null) { parent.removeContent(i); parent.addContent(i, replacement); i--; // Process replacement content } else { processChildren(file, child); } } }
/** * @param element * {@link org.jdom2.Element} * @return {@link List}<{@link String}> * @author sholzer (05.05.2015) */ public List<Text> getTextNodes(Element element) { List<Text> result = new LinkedList<>(); for (Content content : element.getContent()) { if (content instanceof Text) { result.add((Text) content); } } return result; }
/** * Returns all child elements of the given Element regardless of their Namespaces * @param element * {@link Element} * @return {@link List}<{@link Element}> * @author sholzer (13.05.2015) */ public List<Element> getChildrenFromElement(Element element) { List<Element> result = new LinkedList<>(); for (Content c : element.getContent()) { if (c instanceof Element) { result.add((Element) c); } } return result; }
public static MCRChangeData swap(Element parent, int posA, Content a, int posB, Content b) { if (posA > posB) return swap(parent, posB, b, posA, a); b.detach(); // x a x x x parent.addContent(posA, b); // x b a x x x a.detach(); // x b x x x parent.addContent(posB, a); // x b x x a x return new MCRChangeData("swapped-elements", posA + " " + posB, posB, parent); }
/** * @return the mods:mods Element at /metadata/def.modsContainer/modsContainer */ public Element getMODS() { try { MCRMetaXML mx = (MCRMetaXML) (object.getMetadata().getMetadataElement(DEF_MODS_CONTAINER).getElement(0)); for (Content content : mx.getContent()) { if (content instanceof Element) { return (Element) content; } } } catch (NullPointerException | IndexOutOfBoundsException e) { //do nothing } return null; }
public void addContent(Content content) { if (this.content == null) { this.content = new ArrayList<>(); } this.content.add(content); }
/** * This method create a XML stream for all data in this class, defined by * the MyCoRe XML MCRMetaLangText definition for the given subtag. * * @exception MCRException * if the content of this class is not valid * @return a JDOM Element with the XML MCRMetaLangText part */ @Override public org.jdom2.Element createXML() throws MCRException { Element elm = super.createXML(); List<Content> addedContent = new ArrayList<>(content.size()); cloneListContent(addedContent, content); elm.addContent(addedContent); return elm; }
/** * Adds a section to the MyCoRe webpage * @param title the title of the section * @param content list of content added to the section * @param lang the language of the section specified by a language key. * @return added section */ public Element addSection(String title, List<Content> content, String lang) { Element section = new Element(XML_SECTION); if (lang != null) { section.setAttribute(XML_LANG, lang, Namespace.XML_NAMESPACE); } if (title != null && !title.equals("")) { section.setAttribute(XML_TITLE, title); } section.addContent(content); this.xml.getRootElement().addContent(section); return section; }
public static boolean equivalentContent(List<Content> l1, List<Content> l2) { if (l1.size() != l2.size()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Number of content list elements differ {}!={}", l1.size(), l2.size()); } return false; } boolean result = true; Iterator<Content> i1 = l1.iterator(); Iterator<Content> i2 = l2.iterator(); while (result && i1.hasNext() && i2.hasNext()) { Object o1 = i1.next(); Object o2 = i2.next(); if (o1 instanceof Element && o2 instanceof Element) { result = equivalent((Element) o1, (Element) o2); } else if (o1 instanceof Text && o2 instanceof Text) { result = equivalent((Text) o1, (Text) o2); } else if (o1 instanceof Comment && o2 instanceof Comment) { result = equivalent((Comment) o1, (Comment) o2); } else if (o1 instanceof ProcessingInstruction && o2 instanceof ProcessingInstruction) { result = equivalent((ProcessingInstruction) o1, (ProcessingInstruction) o2); } else if (o1 instanceof DocType && o2 instanceof DocType) { result = equivalent((DocType) o1, (DocType) o2); } else { result = false; } } return result; }
/** * This method is capable of serializing Elements and Text nodes. * Return null otherwise. * * @param content the content to serialize * @return the serialized content, or null if the type is not supported */ public static JsonElement serialize(Content content) { if (content instanceof Element) { return serializeElement((Element) content); } if (content instanceof Text) { return serializeText((Text) content); } return null; }
public static List<Content> clone(List<Content> content) { List<Content> cloned = new ArrayList<Content>(); for (Object o : content) { cloned.add((Content) ((Content)o).clone()); } return cloned; }
private static void canonicalizeNamespaces(Element scope, List<Content> content) { Map<String, String> prefixToUri = XmlHelper .getInScopeNamespaceDeclarations(scope); for (Content c : content) { if (c instanceof Element) { canonicalizeNamespace((Element) c, prefixToUri); } } }
private static Element asElement(Content node) { try { return (Element) node; } catch (ClassCastException e) { throw new PatchException(ErrorCondition.INVALID_PATCH_DIRECTIVE, "selected node is not an element"); } }
private static Text getWhitespace(Element parent, int i) { try { Content c = parent.getContent(i); if (isWhitespace(c)) { return (Text) c; } } catch (IndexOutOfBoundsException noSuchSibling) { // invalid whitepace directive } throw new PatchException(ErrorCondition.INVALID_WHITESPACE_DIRECTIVE, "sibling is not a whitespace node"); }
/** * Execute an XPath * * @param document * the Document * @param xpathStr * the Xpath String * @param namespaceStr * the namespace str * @param filter * the filter * @return the list<? extends content> */ static public List<? extends Content> executeXPath(final Object document, final String xpathStr, final String namespaceStr, final Filter<? extends Content> filter) { final XPathFactory xpathFactory = XPathFactory.instance(); // XPathExpression<Object> expr = xpathFactory.compile(xpathStr); XPathExpression<? extends Content> expr = null; if (namespaceStr != null) expr = xpathFactory.compile(xpathStr, filter, null, Namespace.getNamespace("x", namespaceStr)); else expr = xpathFactory.compile(xpathStr, filter); List<? extends Content> xPathSearchedNodes = null; try { xPathSearchedNodes = expr.evaluate(document); } // TODO: Add better handling for these kinds of exceptions catch (final Exception e) { throw new CsfRuntimeException("Error in querying the message", e); } return xPathSearchedNodes; /* * for (int i = 0; i < xPathSearchedNodes.size(); i++) { Content content = * xPathSearchedNodes.get(i); System.out.println("content: " + i + ": " + * content.getValue()); } */ }
private List<Element> getRemainingElements(final int fromIndex, final Element ap) { final List<Element> remains = new ArrayList<>(); for (int i = fromIndex; i < ap.getContentSize(); ++i) { final Content apChild = ap.getContent(i); if (apChild instanceof Element) { final Element apChildElement = (Element) apChild; if (PPTXDocument.R_ELEMENT.equals(apChildElement.getName()) || PPTXDocument.BR_ELEMENT.equals(apChildElement.getName())) { remains.add(apChildElement); } } } return remains; }
/** * Evaluates an XQuery against a data document * @param query the XQuery to evaluate * @param dataElem a JDOM Element containing the data tree * @return a List containing the Element(s) resulting from the evaluation * @throws SaxonApiException if there's a problem with the XQuery or Element */ public static List<Content> evaluateListQuery(String query, Element dataElem) throws SaxonApiException { // put the element in a jdom document Document dataDoc = new Document(dataElem.clone()); String result = evaluateQuery(query, dataDoc); // use the string result to create a doc to get it expressed as an element list Document resultDoc = JDOMUtil.stringToDocument(StringUtil.wrap(result, "root")); return resultDoc.getRootElement().cloneContent(); }
private static void timeMLToNAFNER(KAFDocument kaf, String fileName, String language) { //reading the TimeML xml file SAXBuilder sax = new SAXBuilder(); XPathFactory xFactory = XPathFactory.instance(); try { Document doc = sax.build(fileName); Element rootElement = doc.getRootElement(); XPathExpression<Element> timexExpr = xFactory.compile("//TIMEX3", Filters.element()); List<Element> timexElems = timexExpr.evaluate(doc); XPathExpression<Element> eventExpr = xFactory.compile("//EVENT", Filters.element()); //getting the Document Creation Time Element dctElement = rootElement.getChild("DCT"); Element dctTimex = dctElement.getChild("TIMEX3"); String dctTimexValue = dctTimex.getAttributeValue("value"); kaf.createFileDesc().creationtime = dctTimexValue; //getting the TEXT Element textElement = rootElement.getChild("TEXT"); List<Content> textElements = textElement.getContent(); //we need to iterate over single content of the text element //to get the text and the relevant attributes from TIMEX and //EVENT elements for (Content textElem : textElements) { if (textElem.getCType().equals(CType.Element)) { System.out.println(textElem.getValue()); } } } catch (JDOMException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 将微信XML转换化DBO * * @param xml * MESSAGE XML * @return DBO */ public static BasicDBObject xml2dbo(Document xml) { if (xml == null) return null; List<Element> params = xml.getRootElement().getChildren(); if (params == null || params.size() <= 0) return null; //log.info(xml2str(xml)); BasicDBObject dbo = new BasicDBObject(); for (Element e : params) { List<Content> cs = e.getContent(); if (cs != null && cs.size() > 0) { for (Content c : cs) { if (c != null) { Object o = null; switch (c.getCType()) { case Text: case CDATA: o = c.getValue(); break; default:; } if (!CommonUtil.isEmpty(o)) { if (e.getName().equalsIgnoreCase("createtime")) o = Integer.parseInt(o.toString()); dbo.append(e.getName(), o); } } } } } return dbo; }
private org.jdom2.Document replaceVars(TemplateNode root) { org.jdom2.Document doc = new org.jdom2.Document(); Content c = replaceVarsRecursive(root); doc.setContent(c); return doc; }
protected String getXmlInnerText(final Element e) { final StringBuffer sb = new StringBuffer(); final XMLOutputter xo = new XMLOutputter(); final List<Content> children = e.getContent(); sb.append(xo.outputString(children)); return sb.toString(); }
private void asserEqualContent(final Element one, final Element two) { final List<Content> oneContent = one.getContent(); final List<Content> twoContent = two.getContent(); if (bothNull(oneContent, twoContent)) { return; } assertNullEqual("missing compare content", oneContent, twoContent); assertEqualAttributes(one, two); // scan through the content to make sure each element is equal for (final Object content1 : oneContent) { if (content1 instanceof Element) { final Element e1 = (Element) content1; boolean foundEqual = false; final ArrayList<String> messages = new ArrayList<String>(); for (final Object o : twoContent) { if (o instanceof Element) { final Element e2 = (Element) o; try { // have to check all elements to be order insensitive if (e1.getName().equals(e2.getName()) && equalAttributes(e1, e2, false)) { assertEqualElements(e1, e2); foundEqual = true; messages.clear(); break; } } catch (final Error e) { messages.add(e.getMessage()); } } } // look for the content in the other tree assertTrue("could not find matching element for: " + one.getName(), foundEqual); } } }