1 15 16 package com.ibm.webdav; 17 18 import org.w3c.dom.*; 19 20 21 28 public class XMLUtility { 29 public XMLUtility() { 30 } 31 32 public static String printNode(Node node) { 33 StringBuffer sBuffer = new StringBuffer (); 34 35 printNode(sBuffer, node); 36 37 return sBuffer.toString(); 38 } 39 40 45 private static void printNode(StringBuffer sBuffer, Node node) { 46 if (node.getNodeType() == Node.TEXT_NODE) { 47 sBuffer.append(encodeXMLText(node.getNodeValue().trim())); 48 } else if (node.getNodeType() == Node.CDATA_SECTION_NODE) { 49 sBuffer.append("<![CDATA["); 50 sBuffer.append(node.getNodeValue()); 51 sBuffer.append("]]>"); 52 } else if (node.getNodeType() == Node.ELEMENT_NODE) { 53 Element el = (Element) node; 54 55 sBuffer.append("<").append(el.getTagName()); 56 57 NamedNodeMap attribs = el.getAttributes(); 58 59 for (int i = 0; i < attribs.getLength(); i++) { 60 Attr nextAtt = (Attr) attribs.item(i); 61 sBuffer.append(" ").append(nextAtt.getName()).append("=\"") 62 .append(nextAtt.getValue()).append("\""); 63 } 64 65 NodeList nodes = node.getChildNodes(); 66 67 if (nodes.getLength() == 0) { 68 sBuffer.append("/>"); 69 } else { 70 sBuffer.append(">"); 71 72 for (int i = 0; i < nodes.getLength(); i++) { 73 printNode(sBuffer, nodes.item(i)); 74 } 75 76 sBuffer.append("</").append(el.getTagName()).append(">"); 77 } 78 } 79 } 80 81 87 public static String encodeXMLText(String sText) { 88 StringBuffer sBuff2 = new StringBuffer (sText); 89 StringBuffer sNewBuff = new StringBuffer (); 90 91 for (int i = 0; i < sBuff2.length(); i++) { 92 char currChar = sBuff2.charAt(i); 93 Character currCharObj = new Character (sBuff2.charAt(i)); 94 if (currChar == '&') { 95 if ((sBuff2.length() - 1 - i) >= 4 96 && sBuff2.charAt(i + 1) == 'a' 97 && sBuff2.charAt(i + 2) == 'm' 98 && sBuff2.charAt(i + 3) == 'p' 99 && sBuff2.charAt(i + 4) == ';') { 100 i = i + 4; 101 sNewBuff.append("&"); 102 } else { 103 sNewBuff.append("&"); 104 } 105 } else if (currChar == '>') { 106 sNewBuff.append(">"); 107 } else if (currChar == '<') { 108 sNewBuff.append("<"); 109 } else { 110 sNewBuff.append(currChar); 111 } 112 } 113 114 return sNewBuff.toString(); 115 116 } 117 } | Popular Tags |