Java XML Element Text Set setElementContent(final Node n, final String s)

Here you can find the source of setElementContent(final Node n, final String s)

Description

Replace the content for the current element.

License

Apache License

Parameter

Parameter Description
n element
s string content

Exception

Parameter Description
SAXException an exception

Declaration

public static void setElementContent(final Node n, final String s) throws SAXException 

Method Source Code

//package com.java2s;
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig licenses this file to you 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:/*from  ww w.  ja  v a  2  s. co  m*/
    
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.
*/

import org.w3c.dom.Document;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Main {
    /** Replace the content for the current element.
     *
     * @param n element
     * @param s string content
     * @throws SAXException
     */
    public static void setElementContent(final Node n, final String s) throws SAXException {
        NodeList children = n.getChildNodes();

        for (int i = 0; i < children.getLength(); i++) {
            Node curnode = children.item(i);

            n.removeChild(curnode);
        }

        Document d = n.getOwnerDocument();

        final Node textNode = d.createTextNode(s);

        n.appendChild(textNode);
    }
}

Related

  1. setElementAttr(Element element, String attr, String attrVal)
  2. setElementSimpleValue(Element element, String simpleValue)
  3. setElementsTextNodeValue(Node element, String value)
  4. setElementText(Element element, String text)
  5. setElementText(Element element, String value)