Quantcast
Channel: Delphi Programming – The curse of Dennis D. Spreen
Viewing all articles
Browse latest Browse all 19

VerySimpleXML – a lightweight Delphi XML reader and writer

$
0
0

There are lot of possibilities if you’re in need to parse or write XML files:

Now here comes another one: VerySimpleXML – a lightweight, one-unit XML reader/writer in under 500 600 lines of code. Use it for small well-formed XML files (like configuration files, etc.).

Download verysimplexml-v1.1.zip (7kb)
Download verysimplexml-v1.0.zip (7kb)

What’s new:
v1.1 – 2012/05/01
changed class name to reflect unit naming (class is now called
TXmlVerySimple instead TVerySimpleXml)
- it uses TStreamReader to read line by line instead of reading the
whole file at once (this allows parsing of big xml files with little
additional memory)
- automatically escapes/unescapes not allowed chars (>, <, ", &), thus
removes the most-hated "- escaping introduced in v1.0

Some usage examples:

uses Xml.VerySimple;
 
var
  Xml: TXmlVerySimple;
  Node, Child: TXmlNode;
begin
  Xml := TXmlVerySimple.Create;
  Xml.LoadFromFile('example.xml');
  Xml.Root.Find('book', 'id', 'bk102').Find('author').Text := 'Dein, Carol';
  Node := Xml.Root.AddChild('book');
  Child := Node.AddChild('author');
  Child.Text := 'Barger, Al';
  Child.Attribute['type'] := 'topseller';
  Node.AddChild('title').SetAttribute('lang', 'en').SetText('A big View');
  Xml.SaveToFile('output.xml');
  Xml.Free;
end;

VerySimpleXML supports just a subset of the XML specification

  • load and save from stream or file
  • nodes, childs and attributes
  • UTF-8 and ANSI encoding
  • compact output by setting Xml.Ident := ”;
  • method chaining
  • “>” and “>” inside text and attribute values when wrapped in quotation marks (XML-spec requires you to transform them into &lt; etc.)now automatically escaped with v1.1

It does NOT support:

  • CDATA, comments, etc…

Example XML-file:

<?xml version="1.0" encoding="utf-8" ?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title/>
    <keywords />
  </book>
  <book id=bk102 lang="en">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <description>A former architect battles corporate zombies</description>
    <keywords>
      <keyword lang="es">no-muerto</keyword>
      <keyword lang=en>zombies</keyword>
    </keywords>
  </book>
  <book id="bk103">
    <author rate="&gt;5">Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <description>The collapse of a <nanotechnology> society</description>
  </book>
</catalog>

Warning! This is not a standard well-formed XML file (not all attributes are wrapped with quotation marks, < and > are used within attributes and text), it is an example of the (very simple) fault tolerance of VerySimpleXML. Version 1.1 automatically escapes all non allowed chars.


Viewing all articles
Browse latest Browse all 19

Trending Articles