Java examples for XML:XML Element Value
Returns the string content of XML element (e.g., xsl:value-of() except that the markup of sub elements is included in the string).
/**/*from ww w . j a v a2 s. c o m*/ * Copyright (c) 2009 DITA2InDesign project (dita2indesign.sourceforge.net) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //package com.java2s; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main { /** * Returns the string content of an element (e.g., xsl:value-of() except * that the markup of subelements is included in the string). * @param elem Element to get the value of. */ public static String getElementContent(Element elem) { String resultStr = ""; if (elem != null) { NodeList childs = elem.getChildNodes(); for (int i = 0; i < childs.getLength(); i++) { Node child = childs.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { resultStr = resultStr + echoStartTag((Element) child); resultStr = resultStr + getElementContent((Element) child); resultStr = resultStr + echoEndTag((Element) child); } else if (child.getNodeType() == Node.TEXT_NODE) { resultStr = resultStr + ((Text) child).getData(); } // Else: ignore other node types } } return resultStr; } public static String echoStartTag(Element elem) { String resultStr = "<" + elem.getTagName(); String attstr = ""; NamedNodeMap atts = elem.getAttributes(); for (int j = 0; j < atts.getLength(); j++) { Attr att = (Attr) (atts.item(j)); // FIXME: doesn't account for '"' within attribute value. attstr = attstr + " " + att.getNodeName() + "=\"" + att.getNodeValue() + "\""; } resultStr = resultStr + attstr + ">"; return resultStr; } public static String echoEndTag(Element elem) { return "</" + elem.getTagName() + ">"; } }