001/* 002 Licensed to the Apache Software Foundation (ASF) under one 003 or more contributor license agreements. See the NOTICE file 004 distributed with this work for additional information 005 regarding copyright ownership. The ASF licenses this file 006 to you under the Apache License, Version 2.0 (the 007 "License"); you may not use this file except in compliance 008 with the License. You may obtain a copy of the License at 009 010 http://www.apache.org/licenses/LICENSE-2.0 011 012 Unless required by applicable law or agreed to in writing, 013 software distributed under the License is distributed on an 014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 KIND, either express or implied. See the License for the 016 specific language governing permissions and limitations 017 under the License. 018 */ 019package org.apache.wiki.render; 020 021import java.io.IOException; 022import java.util.Iterator; 023import java.util.List; 024 025import org.apache.log4j.Logger; 026import org.apache.wiki.WikiContext; 027import org.apache.wiki.parser.WikiDocument; 028import org.jdom2.JDOMException; 029import org.jdom2.Text; 030import org.jdom2.xpath.XPath; 031 032/** 033 * A simple renderer that just renders all the text() nodes from the DOM tree. 034 * This is very useful for cleaning away all of the XHTML. 035 * 036 * @since 2.4 037 */ 038public class CleanTextRenderer 039 extends WikiRenderer 040{ 041 private static final String ALL_TEXT_NODES = "//text()"; 042 043 protected static final Logger log = Logger.getLogger( CleanTextRenderer.class ); 044 045 /** 046 * Create a renderer. 047 * 048 * @param context A WikiContext in which the rendering will take place. 049 * @param doc The WikiDocument which shall be rendered. 050 */ 051 public CleanTextRenderer( WikiContext context, WikiDocument doc ) 052 { 053 super( context, doc ); 054 } 055 056 /** 057 * {@inheritDoc} 058 */ 059 public String getString() throws IOException 060 { 061 StringBuilder sb = new StringBuilder(); 062 063 try 064 { 065 XPath xp = XPath.newInstance( ALL_TEXT_NODES ); 066 067 List nodes = xp.selectNodes(m_document.getDocument()); 068 069 for( Iterator i = nodes.iterator(); i.hasNext(); ) 070 { 071 Object el = i.next(); 072 073 if( el instanceof Text ) 074 { 075 sb.append( ((Text)el).getValue() ); 076 } 077 } 078 } 079 catch( JDOMException e ) 080 { 081 log.error("Could not parse XPATH expression"); 082 throw new IOException( e.getMessage() ); 083 } 084 085 return sb.toString(); 086 } 087}