Java XML CDATA Get getChildCdata(Node element, String name)

Here you can find the source of getChildCdata(Node element, String name)

Description

get Child Cdata

License

Open Source License

Declaration

private static String getChildCdata(Node element, String name) 

Method Source Code

//package com.java2s;
/*/*from w w  w  . ja v  a  2 s . c  o  m*/
 // This software is subject to the terms of the Eclipse Public License v1.0
 // Agreement, available at the following URL:
 // http://www.eclipse.org/legal/epl-v10.html.
 // You must accept the terms of that agreement to use this software.
 //
 // Copyright (C) 2011-2011 Pentaho
 // All Rights Reserved.
 */

import org.w3c.dom.*;

import java.util.*;

public class Main {
    private static String getChildCdata(Node element, String name) {
        for (Node node : iter(element.getChildNodes())) {
            if (node.getNodeName().equals(name)) {
                StringBuilder buf = new StringBuilder();
                textRecurse(node, buf);
                return buf.toString();
            }
        }
        return null;
    }

    private static Iterable<Node> iter(final NodeList nodeList) {
        return new Iterable<Node>() {
            public Iterator<Node> iterator() {
                return new Iterator<Node>() {
                    int pos = 0;

                    public boolean hasNext() {
                        return pos < nodeList.getLength();
                    }

                    public Node next() {
                        return nodeList.item(pos++);
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }

    private static void textRecurse(Node node, StringBuilder buf) {
        for (Node node1 : iter(node.getChildNodes())) {
            if (node1.getNodeType() == Node.CDATA_SECTION_NODE
                    || node1.getNodeType() == Node.TEXT_NODE) {
                buf.append(quoteHtml(node1.getTextContent()));
            }
            if (node1.getNodeType() == Node.ELEMENT_NODE) {
                buf.append("<").append(node1.getNodeName()).append(">");
                textRecurse(node1, buf);
                buf.append("</").append(node1.getNodeName()).append(">");
            }
        }
    }

    private static String quoteHtml(String s) {
        return s.replaceAll("&", "&amp;").replaceAll(">", "&gt;")
                .replaceAll("<", "&lt;");
    }
}

Related

  1. getCDATA(Element elem)
  2. getCdata(Element elem)
  3. getCData(Element element)
  4. getCDataNode(Element element)
  5. getCDataValue(Node node, String tag)
  6. getChildCharacterData(Element parentEl)
  7. getChildCharacterData(Element parentEl)
  8. getElementCDATAByTagName(Element current, String name, String namespace)