Using Delphi7 TClientDataSet: is it possible to keep this XML content indented

I use Delphi7 ClientDataSet to read and write xml files for some of my data.

Howerver, when I want to view this outside the program (double-clicking xml in Windows Explorer), I get an "Invalid character found in text content. Resource processing error '- even though the data is being read and written within Delphi.

Is there a way to get TClientDataSet to write indented content on one line?

That way, I could easily open it in a text editor and find which character would cause the above error.

In any case: I find it much more understandable for an XML file that needs to be written with CR / LF and indented anyway.

thanks in advance.

+4
source share
3 answers

This is because the correct encoding (for example, <?xml version="1.0" encoding="UTF-8"?> ) Is not specified in your output file, but it contains some of the characters with incompatible encoding.

As RRUZ mentioned , explicitly specifying TDataPacketFormat as dfXMLUTF8 , when writing a file will certainly solve the "Invalid character" error because it will write first enter the encoding:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <DATAPACKET Version="2.0">[...]
You can also add the encoding manually at the beginning of the file for existing files.

Regarding readable formatting, some readers may read a raw single-line font and make formatting for you (browsers like FireFox or Internet Exporer, and XML editors like XMLNotePad )

+4
source

When you use the TCustomClientDataSet.SaveToFile procedure, you can select the output format; for the default value, this is the dfBinary value, which encodes data in binary format.

  procedure TCustomClientDataSet.SaveToFile(const FileName: string = ''; Format: TDataPacketFormat = dfBinary); 

try changing the Format parameter to dfXML or dfXMLUTF8

 ClientDataSet1.SaveToFile('file.xml',dfXML); 

if you want to format the XML output, you can use the FormatXMLData function FormatXMLData try this code

 uses XMLDoc; Procedure FormatXMLFile(XmlFile:string); var oXml : TXMLDocument; begin oXml := TXMLDocument.Create(nil); try oXml.LoadFromFile(XmlFile); oXml.XML.Text:=xmlDoc.FormatXMLData(oXml.XML.Text); oXml.Active := true; oXml.SaveToFile(XmlFile); finally oXml := nil; end; end; 

finally you will look like this:

  ClientDataSet1.SaveToFile('test.xml',dfXML); FormatXMLFile('test.xml'); 
+7
source

I changed your code because I had some problems with UTF-8:

 Procedure FormatXMLFile(XmlFile:string); var oXml : TXMLDocument; s : utf8String; begin oXml := TXMLDocument.Create(nil); try oXml.LoadFromFile(XmlFile); s := oxml.XML.Text; s := StringReplace(s, '><', '>' + #13#10 + '<' , [rfReplaceAll]); //oXml.XML.Text:=xmlDoc.FormatXMLData(oxml.XML.Text); oxml.XML.Text := s; oXml.Active := true; oXml.SaveToFile(XmlFile); finally oXml := nil; end; end; 
0
source

All Articles