Search code examples
javanode.jsxmlxml-parsingpretty-print

(Node.js/Java) How to make XML output Pretty


i have been trying to make output pretty in XML but not able to do so i want to do this in node.js as well as in java(android).

My XML Input is:

  <custom.TextView 
  android:id="@+id/textView2" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:text="TextView" tools:layout_editor_absoluteX="164dp" /> 

After parsing this code, output is

<custom.TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content"  android:text="TextView" tools:layout_editor_absoluteX="164dp" /> 

And my expected output is

 <custom.TextView 
  android:id="@+id/textView2" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:text="TextView" tools:layout_editor_absoluteX="164dp" /> 

how can i do this pleas help me !


Solution

  • Although approach used in this scenario is not very good but you can try this code for pretty output, in below code you can provide your xml, it'll then beautify it as you desire.

        var arrayEml= xml = '';
    
        for (var i = 0; i < xml.length; i++) {
            if ((xml[i].match(/[a-zA-Z]/)) && (xml[i + 1] == ' ') && (xml[i + 2].match(/[a-zA-Z]/))) {
                arrayEml += (xml[i] + '\n');
            } else {
                arrayEml += xml[i];
            }
            // }
        }
        var againParsing = ' ';
        for (var i = 0; i < arrayEml.length; i++) {
    
            if ((xml[i] = '"') && (xml[i + 1] == ' ') && (xml[i + 2].match(/[a-zA-Z]/))) {
                againParsing += (xml[i] + '\n' + "\t   ");
            } else {
                againParsing += xml[i];
            }
        }