title: Java -Reverse XML attributes
body: <p>The below code is to reverse the XML using DOM parser. Everything works fine but the problem is the attributes not reversing
  for ex:
  &lt;element att1="foo" att2="bar" />
  result should be
  &lt;element att2="bar" att2="foo" /></p>
  
  <p>How to reverse the XML attributes??</p>
  
  <pre><code>public static void main(String[] args) throws Exception {
      reverseChildElements();
  }
  
  public static void reverseChildElements() {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      Document doc = null;
      try {
          DocumentBuilder builder = factory.newDocumentBuilder();
          // Parse the input xml file
          doc = builder.parse("file.xml");
          Node firstChild = doc.getFirstChild();
          reverseChildNodes(firstChild);
          doc.replaceChild(firstChild, doc.getFirstChild());
          outputXml(doc);
      } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) {
          e.printStackTrace();
      }
  }
  
  private static void reverseChildNodes(Node firstChild) {
      NodeList childNodes = firstChild.getChildNodes();
      Stack&lt;Node&gt; nodeStack = new Stack&lt;Node&gt;();
      // Put all the nodes into a Stack
      for (int i = 0; i &lt; childNodes.getLength(); i++) {
          reverseChildNodes(childNodes.item(i));
          revereseAttributes(childNodes.item(i));
          nodeStack.push(childNodes.item(i));
      }
      // This is the last one which we entered
      while (!nodeStack.empty()) {
          firstChild.appendChild(firstChild.removeChild(nodeStack.pop()));
      }
  }
  
  private static void revereseAttributes(Node item) {
      if(item.hasAttributes() &amp;&amp; item.getAttributes().getLength() &gt; 1){
          NamedNodeMap attributesMap = item.getAttributes();
          List&lt;Node&gt; nodeStack = new ArrayList&lt;Node&gt;();
          for (int i = 0; i &lt; attributesMap.getLength(); i++) {
              nodeStack.add(attributesMap.item(i));
          }
          for (Node node : nodeStack) {
              attributesMap.removeNamedItem(node.getNodeName());
              Attr atr = node.getOwnerDocument().createAttribute(node.getNodeName());
              atr.setValue(node.getNodeValue());
              attributesMap.setNamedItem(atr);
          }
      }
  
  }
  
  private static void outputXml(Document doc) throws TransformerException {
      TransformerFactory tf = TransformerFactory.newInstance();
      StringWriter writer = null;
          Transformer transformer = tf.newTransformer();
          transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                  "yes");
          writer = new StringWriter();
  
          transformer.transform(new DOMSource(doc), new StreamResult(writer));
      System.out.println(writer.toString().replaceAll( "(?s)&lt;!--.*?--&gt;", "" ));
  }
  </code></pre>