Search code examples
delphidelphi-2009omnixml

omni xml create xml


What is the fastest way to implement a creation of xml file in this format:

<?xml version="1.0" encoding="Unicode" standalone="yes"?>
<A V1="string" V2=String >
  <B>
    <C V3="1" V4="1" V5="0"/>
  </B>
  <C V6="14.25" V7="0.2"/>
  <D>
    <E V8="1" V9="1" V10="2">
    </E>
    <E V8="2" V9="1" V10="2">
       <F V11="a" V12="B">
         <G>0</G>
       </F>
    </E>
    <E V8="1" V9="1" V10="2">
    </E>
    <E V8="2" V9="1" V10="2">
      <F V11="a" V12="B">
        <G>0</G>
      </F>
    </E>
  </D>
</A>

There are a lot of e, where I can generate in iterations.

However I can't seem to grasp the best approach with Omni.

Creating 10 to 20 objects for so much constant seems a mess and too much.

And could you also mention how to set the encoding to generate the file?


Solution

  • This should get you started:

    uses
      OmniXML,
      OmniXMLUtils;
    
    procedure GetEAttr(var v8, v9, v10: integer);
    begin
      v8 := Random(10);
      v9 := Random(10);
      v10 := Random(10);
    end;
    
    procedure TForm54.FormCreate(Sender: TObject);
    var
      i     : integer;
      node1 : IXMLNode;
      node2 : IXMLNode;
      root  : IXMLNode;
      v10   : integer;
      v8    : integer;
      v9    : integer;
      xmlDoc: IXMLDocument;
    begin
      xmlDoc := CreateXMLDoc;
      xmlDoc.AppendChild(xmlDoc.CreateProcessingInstruction('xml', 'version="1.0" encoding="Unicode" standalone="yes"'));
      root := AppendNode(xmlDoc, 'A');
      SetNodeAttr(root, 'V1', 'string');
      SetNodeAttr(root, 'V2', 'string');
      node1 := AppendNode(root, 'B');
      node2 := AppendNode(node1, 'C');
      SetNodeAttr(node2, 'V3', '1');
      SetNodeAttr(node2, 'V4', '1');
      SetNodeAttr(node2, 'V5', '0');
      node1 := AppendNode(root, 'C');
      SetNodeAttr(node1, 'V6', '14.25');
      SetNodeAttr(node1, 'V7', '0.2');
      node1 := AppendNode(root, 'D');
      for i := 1 to 4 do begin
        GetEAttr(v8, v9, v10);
        node2 := AppendNode(node1, 'E');
        SetNodeAttrInt(node2, 'V8', v8);
        SetNodeAttrInt(node2, 'V9', v9);
        SetNodeAttrInt(node2, 'V10', v10);
      end;
      XMLSaveToFile(xmlDoc, 'test.xml', ofIndent);
    end;