TXmlWriter
Source: source/classes/TXmlWriter.prg
TXmlWriter is a minimal streaming XML writer that writes directly to disk. It supports the standard OpenTag / Element / CloseTag pattern and produces well-formed XML with automatic indentation and character escaping. Every method returns Self, enabling a fluent (chainable) API. The writer uses Harbour's low-level file I/O (FCreate / FWrite) so it stays memory-efficient even for large documents.
Key DATA Members
| DATA | Type | Description |
|---|---|---|
cFile | Character | Output file path |
hFile | Numeric | File handle from FCreate ( -1 if creation failed ) |
nIndent | Numeric | Current indentation level (0-based) |
aStack | Array | Tag name stack for nesting; ensures CloseTag knows which tag to close |
lOpen | Logical | File is open and writable |
Methods
| Method | Description |
|---|---|
New( cFile ) | Create a writer and open the output file. Returns Self |
Start( cVersion, cEncoding ) | Write the XML declaration <?xml ... ?>. Defaults: "1.0", "UTF-8". Returns Self |
OpenTag( cTag, hAttribs ) | Open a named tag with optional hash of attributes. Increases indent. Returns Self |
CloseTag( cTag ) | Close the most recent (or named) tag. Decreases indent. Returns Self |
Element( cTag, cValue, hAttribs ) | Write a self-closing tag or a full element with escaped text content. Returns Self |
Comment( cText ) | Write an XML comment <!-- ... -->. Returns Self |
CData( cText ) | Write a CDATA section <![CDATA[...]]>. Returns Self |
End() | Close any remaining open tags to ensure well-formed output. Returns Self |
Destroy() | Close the file handle if still open |
Example: Generate XML
#include "FiveWin.ch"
function Main()
local oXml := TXmlWriter():New( "catalog.xml" )
oXml:Start()
oXml:OpenTag( "catalog", { "version" -> "1.0" } )
oXml:OpenTag( "book", { "id" -> "101" } )
oXml:Element( "title", "FiveWin Programming" )
oXml:Element( "author", "Antonio Linares" )
oXml:Element( "price", "49.95", { "currency" -> "USD" } )
oXml:CloseTag( "book" )
oXml:CloseTag( "catalog" )
oXml:End()
oXml:Destroy()
return nil
Notes
- All public methods (except
NewandDestroy) returnSelf, which allows method chaining:oXml:Start():OpenTag(...):Element(...):CloseTag():End(). - Attribute hashes use the
key -> valuesyntax (Harbour hashes). Values are automatically escaped for XML. - The
Escape()method handles five predefined XML entities:&,<,>,", and'. End()automatically closes any tags remaining on the stack, ensuring well-formed output even if the caller omitted explicit close calls.- The writer uses two-space indentation per nesting level, controlled by
cIndStr.