1 11 12 package org.eclipse.ui.internal.cheatsheets.composite.parser; 13 14 import org.w3c.dom.NamedNodeMap ; 15 import org.w3c.dom.Node ; 16 import org.w3c.dom.NodeList ; 17 18 public class MarkupParser { 19 20 public static String parseAndTrimTextMarkup(Node parentNode) { 21 return parseMarkup(parentNode).trim(); 22 } 23 24 private static String parseMarkup(Node parentNode) { 25 NodeList children = parentNode.getChildNodes(); 26 StringBuffer text = new StringBuffer (); 27 for (int i = 0; i < children.getLength(); i++) { 28 Node childNode = children.item(i); 29 if (childNode.getNodeType() == Node.TEXT_NODE) { 30 text.append(escapeText(childNode.getNodeValue())); 31 } else if (childNode.getNodeType() == Node.ELEMENT_NODE) { 32 text.append('<'); 33 text.append(childNode.getNodeName()); 34 NamedNodeMap attributes = childNode.getAttributes(); 36 if (attributes != null) { 37 for (int x = 0; x < attributes.getLength(); x++) { 38 Node attribute = attributes.item(x); 39 String attributeName = attribute.getNodeName(); 40 if (attributeName == null) 41 continue; 42 text.append(' '); 43 text.append(attributeName); 44 text.append(" = \""); text.append(attribute.getNodeValue()); 46 text.append('"'); 47 } 48 } 49 text.append('>'); 50 text.append(parseMarkup(childNode)); 51 text.append("</"); text.append(childNode.getNodeName()); 53 text.append('>'); 54 } 55 } 56 return text.toString(); 57 } 58 59 public static String escapeText(String input) { 60 StringBuffer result = new StringBuffer (input.length() + 10); 61 for (int i = 0; i < input.length(); ++i) 62 appendEscapedChar(result, input.charAt(i)); 63 return result.toString(); 64 } 65 66 private static void appendEscapedChar(StringBuffer buffer, char c) { 67 String replacement = getReplacement(c); 68 if (replacement != null) { 69 buffer.append(replacement); 70 } else { 71 buffer.append(c); 72 } 73 } 74 75 private static String getReplacement(char c) { 76 switch (c) { 79 case '<' : 80 return "<"; case '>' : 82 return ">"; case '&' : 84 return "&"; case '\t' : 86 return " "; } 88 return null; 89 } 90 91 94 public static String createParagraph(String text, String imageTag) { 95 String result = ""; String trimmed = text.trim(); 97 boolean addParagraphTags = trimmed.length() < 3 || trimmed.charAt(0)!='<' || 98 (trimmed.charAt(1)!='p' && trimmed.charAt(1) != 'l'); 99 if (addParagraphTags) { 100 result += "<p>"; } 102 103 if (imageTag != null) { 104 result += "<img HREF=\""; result += imageTag; 106 result += "\"/> "; } 108 109 result += trimmed; 110 111 if (addParagraphTags) { 112 result += "</p>"; } 114 return result; 115 } 116 117 } 118 | Popular Tags |