Set the XML attribute value under the specified name, if the given value is neither null nor an empty String . - Java XML

Java examples for XML:XML Attribute

Description

Set the XML attribute value under the specified name, if the given value is neither null nor an empty String .

Demo Code

/*//from  ww w.ja v a2s.  co  m
   Copyright (C) 2016 HermeneutiX.org

   This file is part of SciToS.

   SciToS 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.

   SciToS 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 SciToS. If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

import org.w3c.dom.Element;

public class Main {
    /**
     * Set the attribute value under the specified name, if the given value is neither {@code null} nor an empty {@code String}.
     *
     * @param node
     *            element to set the attribute on
     * @param attributeName
     *            name of the targeted attribute
     * @param attributeValue
     *            value to set (method does nothing if this is {@code null} or an empty {@code String}
     * @return if the attribute has been set
     */
    public static boolean setNullableAttribute(final Element node,
            final String attributeName, final Object attributeValue) {
        if (attributeValue != null) {
            final String textValue = attributeValue.toString();
            if (!textValue.isEmpty()) {
                node.setAttribute(attributeName, textValue);
                return true;
            }
        }
        return false;
    }
}

Related Tutorials