code: public static String encode(String name)
     {
        // quick check for root node name
        if (name.length() == 0)
        {
           return name;
        }
        if (XMLChar.isValidName(name) && name.indexOf("_x") < 0)
        {
           // already valid
           return name;
        }
        else
        {
           // encode
           StringBuilder encoded = new StringBuilder();
           for (int i = 0; i < name.length(); i++)
           {
              if (i == 0)
              {
                 // first character of name
                 if (XMLChar.isNameStart(name.charAt(i)))
                 {
                    if (needsEscaping(name, i))
                    {
                       // '_x' must be encoded
                       encode('_', encoded);
                    }
                    else
                    {
                       encoded.append(name.charAt(i));
                    }
                 }
                 else
                 {
                    // not valid as first character -> encode
                    encode(name.charAt(i), encoded);
                 }
              }
              else if (!XMLChar.isName(name.charAt(i)))
              {
                 encode(name.charAt(i), encoded);
              }
              else
              {
                 if (needsEscaping(name, i))
                 {
                    // '_x' must be encoded
                    encode('_', encoded);
                 }
                 else
                 {
                    encoded.append(name.charAt(i));
                 }
              }
           }
           return encoded.toString();
        }
     }
docs: Encodes <code>name</code> as specified in ISO 9075.
  
  @param name
  the <code>String</code> to encode.
  @return the encoded <code>String</code> or <code>name</code> if it does not need encoding.