Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reformat XML programmatically?

Tags:

xml

delphi

msxml

I have an XML document on input which is awfully formatted (it's Delphi project file if anyone cares) - inconsistent indenting, empty lines, strings of nodes lumped together:

<BorlandProject><Delphi.Personality><Parameters><Parameters Name="HostApplication">C:\Some\Path\Filename.exe</Parameters> <!--etc--> <Excluded_Packages>


</Excluded_Packages>

I want to reformat it into something nice. What's the easiest way to do that programmatically, with Win32/COM? If MSXML, how do I go about it?

I'd like to be able to specify indentation unit too (tab/several spaces).

I tried using Delphi's MSXML wrapper TXmlDocument and it does indeed delete the empty lines and indent nodes with tabs, but it does not split lines like this one:

<BorlandProject><Delphi.Personality><Parameters><Parameters Name="HostApplication">C:\Some\Path\Filename.exe</Parameters> <!--etc--> <Excluded_Packages>
like image 395
himself Avatar asked Nov 29 '10 15:11

himself


1 Answers

I tested the FormatXMLData function in a delphi project file and works ok, indent all the lines correctly.

check this code.

uses
 XMLIntf,
 XMLDoc;

Procedure FormatXMLFile(const XmlFile:string);
var
   oXml : IXMLDocument;
 begin
   oXml := TXMLDocument.Create(nil);
   oXml.LoadFromFile(XmlFile);
   oXml.XML.Text:=xmlDoc.FormatXMLData(oXml.XML.Text);
   oXml.Active := true;
   oXml.SaveToFile(XmlFile);
 end;
like image 191
RRUZ Avatar answered Oct 28 '22 18:10

RRUZ