Java tutorial
//package com.java2s; //License from project: Apache License import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Node; public class Main { public static void addAttribute(Document document, Node node, String attName, boolean attValue) { addAttribute(document, node, attName, attValue ? "true" : "false"); } public static void addAttribute(Document document, Node node, String attName, int attValue) { addAttribute(document, node, attName, Integer.toString(attValue)); } public static void addAttribute(Document document, Node node, String attName, String attValue) { Attr attr = document.createAttribute(attName); attr.setNodeValue(removeXMLInvalidChars(attValue)); node.getAttributes().setNamedItem(attr); } public static String removeXMLInvalidChars(String input) { String xml10pattern = "[^" + "\u0009\r\n" + "\u0020-\uD7FF" + "\uE000-\uFFFD" + "\ud800\udc00-\udbff\udfff" + "]"; return input.replaceAll(xml10pattern, ""); } }