Java examples for XML:XML Element Child
Transform xml element and children into a string
/******************************************************************************* * Copyright (c) 2015-2016 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //package com.java2s; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** Transform xml element and children into a string */* w w w.j a va 2 s.c o m*/ * @param nd Node root of elements to transform * @return String representation of xml */ public static String elementToString(Node nd, boolean add_newlines) { //short type = n.getNodeType(); if (Node.CDATA_SECTION_NODE == nd.getNodeType()) { return "<![CDATA[" + nd.getNodeValue() + "]]>"; } // return if simple element type final String name = nd.getNodeName(); if (name.startsWith("#")) { if (name.equals("#text")) return nd.getNodeValue(); return ""; } // output name String ret = "<" + name; // output attributes NamedNodeMap attrs = nd.getAttributes(); if (attrs != null) { for (int idx = 0; idx < attrs.getLength(); idx++) { Node attr = attrs.item(idx); ret += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\""; } } final String text = nd.getTextContent(); final NodeList child_ndls = nd.getChildNodes(); String all_child_str = ""; for (int idx = 0; idx < child_ndls.getLength(); idx++) { final String child_str = elementToString(child_ndls.item(idx), add_newlines); if ((child_str != null) && (child_str.length() > 0)) { all_child_str += child_str; } } if (all_child_str.length() > 0) { // output children ret += ">" + (add_newlines ? "\n" : " "); ret += all_child_str; ret += "</" + name + ">"; } else if ((text != null) && (text.length() > 0)) { // output text ret += text; ret += "</" + name + ">"; } else { // output nothing ret += "/>" + (add_newlines ? "\n" : " "); } return ret; } }