Recent

Author Topic: [SOLVED] XML - inserting a node to existing file  (Read 2539 times)

adamus

  • Newbie
  • Posts: 1
[SOLVED] XML - inserting a node to existing file
« on: January 12, 2019, 04:21:24 pm »
Hello  :)

Based on http://wiki.freepascal.org/XML_Tutorial I tried to insert a new node to an existing document.

Code: XML  [Select][+][-]
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <register>
  3.   <usuario id="001">
  4.     <nome>Fernando</nome>
  5.     <idade>32</idade>
  6.     <item nome="Item" arquivo="Arquivo"/>
  7.   </usuario>
  8.   <item id="002">
  9.       ...
  10.   </item>
  11. </register>
  12.  

I want to insert any item with e.g. id="002" to the existing xml.

I tried:

Code: Pascal  [Select][+][-]
  1. procedure ExportXML();
  2.  var Doc: TXMLDocument;
  3.  NovoNo: TDomNode;
  4. begin
  5.      ReadXMLFile(Doc, 'c:\temp\test.xml');
  6.  
  7.      NovoNo := Doc.CreateElement('item');
  8.      TDOMElement(NovoNo).SetAttribute('nome', 'Item');
  9.      TDOMElement(NovoNo).SetAttribute('arquivo', 'Arquivo');
  10.  
  11.      Doc.DocumentElement.ParentNode.AppendChild(NovoNo);
  12.  
  13.      writeXMLFile(Doc, 'c:\temp\test.xml');
  14.  
  15. end;
  16.  

.. and got an exception. What did I wrong and how can I achieve it just add new nodes to existing documents. Thank you.
« Last Edit: January 12, 2019, 10:41:09 pm by adamus »

Blaazen

  • Hero Member
  • *****
  • Posts: 3237
  • POKE 54296,15
    • Eye-Candy Controls
Re: XML - inserting a node to existing file
« Reply #1 on: January 12, 2019, 04:56:02 pm »
Code: Pascal  [Select][+][-]
  1. procedure ExportXML;
  2. var Doc: TXMLDocument;
  3.     NovoNo: TDomNode;
  4. begin
  5.   ReadXMLFile(Doc, '/media/homeM/v1/Projects/Forum/XMLDemo/test.xml');
  6.  
  7.   NovoNo:=nil;
  8.   NovoNo:=Doc.DocumentElement.FindNode('item');
  9.   if not assigned(NovoNo) then
  10.     begin
  11.       NovoNo:=Doc.CreateElement('item');
  12.       TDOMElement(NovoNo).SetAttribute('ID', '002');
  13.       Doc.DocumentElement.AppendChild(NovoNo);
  14.     end;
  15.  
  16.   writeXMLFile(Doc, '/media/homeM/v1/Projects/Forum/XMLDemo/test.xml');
  17.   Doc.Free;
  18. end;

This works (note that I changed path to file). I recommend to use try..except blocks for reading / writing to file.
Lazarus 2.3.0 (rev main-2_3-2863...) FPC 3.3.1 x86_64-linux-qt Chakra, Qt 4.8.7/5.13.2, Plasma 5.17.3
Lazarus 1.8.2 r57369 FPC 3.0.4 i386-win32-win32/win64 Wine 3.21

Try Eye-Candy Controls: https://sourceforge.net/projects/eccontrols/files/

 

TinyPortal © 2005-2018