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 034 * from the DOM tree. This is very useful for cleaning away 035 * all of the XHTML. 036 * 037 * @since 2.4 038 */ 039public class CleanTextRenderer 040 extends WikiRenderer 041{ 042 private static final String ALL_TEXT_NODES = "//text()"; 043 044 protected static final Logger log = Logger.getLogger( CleanTextRenderer.class ); 045 046 /** 047 * Create a renderer. 048 * 049 * @param context {@inheritDoc} 050 * @param doc {@inheritDoc} 051 */ 052 public CleanTextRenderer( WikiContext context, WikiDocument doc ) 053 { 054 super( context, doc ); 055 } 056 057 /** 058 * {@inheritDoc} 059 */ 060 public String getString() 061 throws IOException 062 { 063 StringBuilder sb = new StringBuilder(); 064 065 try 066 { 067 XPath xp = XPath.newInstance( ALL_TEXT_NODES ); 068 069 List nodes = xp.selectNodes(m_document.getDocument()); 070 071 for( Iterator i = nodes.iterator(); i.hasNext(); ) 072 { 073 Object el = i.next(); 074 075 if( el instanceof Text ) 076 { 077 sb.append( ((Text)el).getValue() ); 078 } 079 } 080 } 081 catch( JDOMException e ) 082 { 083 log.error("Could not parse XPATH expression"); 084 throw new IOException( e.getMessage() ); 085 } 086 087 return sb.toString(); 088 } 089}