Pages

Sunday, October 16, 2011

XML Formatter

Many times I've searched for tools/plugins/libraries to format/indent/... small XML files. A tool to do that can be easily done with classes from System.Xml namespace
try{      
 // Format XML file
 XmlDocument^ doc = gcnew XmlDocument;
 
 char tmpFileName[MAX_PATH] = "";
 GetTempFileName(".", "bak_1", 0, tmpFileName);
 
 // convert unmanaged -> managed
 String^ srcFile = gcnew String(szFileName);
 String^ tmpFile = gcnew String(tmpFileName); 
 
 File::Copy(srcFile, tmpFile, true);
 try{
  doc->Load(tmpFile);
 }
 catch(XmlException^ e1) {
  //convert Managed -> unmanaged
  TCHAR* errMsg = (TCHAR*)(void*)Marshal::StringToHGlobalAnsi(e1->Message);
  MessageBox(NULL, errMsg, "Error", 0);
  return 0;
 }

 XmlWriterSettings^ xws = gcnew XmlWriterSettings;     
 xws->Indent = true;
 xws->CheckCharacters = false;

 XmlWriter^ writer = XmlWriter::Create(srcFile, xws);      
 doc->Save(writer);
 writer->Close();

 File::Delete(tmpFile);
}
catch(Exception ^e) {
 MessageBox(NULL, szFileName, "Exception while converting following files:", 0);
}
MessageBox(NULL, "Converted", "ok", 0);


How nice would be to build your own small tools and adapt them when you need to.   A (very) small step towards being a self sustainable programmer is this :)
http://code.google.com/p/cool-xml/

No comments:

Post a Comment