Java tutorial
//package com.java2s; /******************************************************************************* * Copyright (c) 2012 Firestar Software, Inc. * 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 * * Contributors: * Firestar Software, Inc. - initial API and implementation * * Author: * Gabriel Oancea * *******************************************************************************/ import org.w3c.dom.*; public class Main { /** * Set the text of the specified element to the given string. * * @param e The element. * @param text The text string. */ public static void setText(Element e, String text) { NodeList lst = e.getChildNodes(); int size = lst.getLength(); for (int i = 0; i < size; i++) { Node n = lst.item(i); if (n.getNodeType() == Node.TEXT_NODE) { Text t = (Text) n; t.setData(text.trim()); return; } } Document doc = e.getOwnerDocument(); // bit of a hack - we preserve the cdata on the way in so we can serialize correctly // This only works on xml to xml // TODO need to have a "preserve format" or some such on the mdmi structure if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { CDATASection cdata = doc .createCDATASection(text != null ? text.substring(9, text.lastIndexOf("]]>")) : null); e.appendChild(cdata); } else { Text txt = doc.createTextNode(text != null ? text.trim() : null); e.appendChild(txt); } } }