Java tutorial
//package com.java2s; /******************************************************************************* * Copyright (C) 2006-2013 AITIA International, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main { /** @param text <code>null</code> removes 'subElement' completely */ public static Text setTextField(Element node, String subElement, String text) { NodeList nl = node.getElementsByTagName(subElement); if (nl == null || nl.getLength() == 0) { if (text == null) return null; Document d = node.getOwnerDocument(); Element e = d.createElement(subElement); Text ans = d.createTextNode(text); e.appendChild(ans); node.appendChild(e); return ans; } else if (text != null) { return setText(nl.item(0), text); } else { node.removeChild(nl.item(0)); return null; } } /** * Creates a Text child, or replaces all existing children of type Text. * Non-Text descendants are preserved without change. * @return The Text child which receives the specified text. * @see Node.setTextContent() */ public static Text setText(Node node, String text) { NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0, n = children.getLength(); i < n; ++i) { Node child = children.item(i); if (child instanceof Text) { return ((Text) child).replaceWholeText(text); } } } Text ans = node.getOwnerDocument().createTextNode(text); node.appendChild(ans); return ans; } }