Replaces the value of an entity in an XML string and returns the updated XML string. - Java XML

Java examples for XML:XML String

Description

Replaces the value of an entity in an XML string and returns the updated XML string.

Demo Code

/*---------------------------------------------------------------
 *  Copyright 2005 by the Radiological Society of North America
 *
 *  This source software is released under the terms of the
 *  RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
 *----------------------------------------------------------------*/

import java.io.StringWriter;

public class Main{

    /**/*from   w ww.  java  2  s  .c o m*/
     * Replaces the value of an entity in an XML string
     * and returns the updated XML string.
     * @param xmlString the XML string.
     * @param theName the name of the entity to modify.
     * @param theValue the replacement value for the named entity. If null,
     * no replacement is done.
     * @return the updated XML string.
     */
    public static String setEntity(String xmlString, String theName,
            String theValue) {
        if (theValue != null) {
            int begin = -1;
            int end;
            String name, value;
            while ((begin = xmlString.indexOf("!ENTITY", begin + 1)) != -1) {
                begin = StringUtil.skipWhitespace(xmlString, begin + 7);
                end = StringUtil.findWhitespace(xmlString, begin);
                name = xmlString.substring(begin, end);
                if (name.equals(theName)) {
                    begin = xmlString.indexOf("\"", end) + 1;
                    end = xmlString.indexOf("\"", begin);
                    return xmlString.substring(0, begin) + theValue.trim()
                            + xmlString.substring(end);
                }
            }
        }
        return xmlString;
    }
}

Related Tutorials