List of utility methods to do XML Node to String Convert
String | getStrFromNode(Node xpathnode) Method getStrFromNode if (xpathnode.getNodeType() == Node.TEXT_NODE) { StringBuilder sb = new StringBuilder(); for (Node currentSibling = xpathnode.getParentNode() .getFirstChild(); currentSibling != null; currentSibling = currentSibling .getNextSibling()) { if (currentSibling.getNodeType() == Node.TEXT_NODE) { sb.append(((Text) currentSibling).getData()); return sb.toString(); } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { return ((Attr) xpathnode).getNodeValue(); } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { return ((ProcessingInstruction) xpathnode).getNodeValue(); return null; |
String | elementToString(Node n) element To String String name = n.getNodeName(); short type = n.getNodeType(); if (Node.CDATA_SECTION_NODE == type) { return "<![CDATA[" + n.getNodeValue() + "]]>"; if (name.length() > 0 && name.charAt(0) == '#') { return ""; StringBuilder sb = new StringBuilder(); sb.append('<').append(name); NamedNodeMap attrs = n.getAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); sb.append(' ').append(attr.getNodeName()).append("=\"") .append(encodeXML(attr.getNodeValue())) .append('\"'); String textContent = null; NodeList children = n.getChildNodes(); if (children.getLength() == 0) { if ((textContent = getTextContent(n)) != null && !"".equals(textContent)) { sb.append(encodeXML(textContent)).append("</").append(name) .append('>'); } else { sb.append("/>").append('\n'); } else { sb.append('>').append('\n'); boolean hasValidChildren = false; for (int i = 0; i < children.getLength(); i++) { String childToString = elementToString(children.item(i)); if (!"".equals(childToString)) { sb.append(childToString); hasValidChildren = true; if (!hasValidChildren && ((textContent = getTextContent(n)) != null)) { sb.append(encodeXML(textContent)); sb.append("</").append(name).append('>'); return sb.toString(); |