title: How to add an attribute to the root node
body: <p>I have an xml as <code>String</code></p>
  
  <pre><code>&lt;color&gt;
      &lt;name&gt;black&lt;/name&gt;
  &lt;color&gt;
  </code></pre>
  
  <p>I want to add an attribute to root node and save a xml as String again.</p>
  
  <pre><code>&lt;color id="1"&gt;
      &lt;name&gt;black&lt;/name&gt;
  &lt;color&gt;
  </code></pre>
  
  <p>But I can't. Here is my code</p>
  
  <pre><code>import javax.xml.parsers.DocumentBuilder;
  import javax.xml.parsers.DocumentBuilderFactory;
  import org.xml.sax.InputSource;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  
  String xml = "&lt;color&gt;&lt;name&gt;black&lt;/name&gt;&lt;/color&gt;";
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  InputSource is = new InputSource(new StringReader(xml));
  Document document = builder.parse(is);
  Element element = (Element) document.getFirstChild();
  element.setAttribute("id", "1");
  String result = document.toString();
  System.out.println(result);
  </code></pre>
  
  <p>The output is [#document: null]. Help me please resolve my problem</p>