Recent

Author Topic: How to merge a nodes from two different xml files using DOM library  (Read 3342 times)

Wujek

  • New Member
  • *
  • Posts: 10
I have been looking for a way to merge two different xml files in one file, or move a node from one to another. It is possible using DOM ? If yes, please give me an example.

Regards
Zbig

Leledumbo

  • Hero Member
  • *****
  • Posts: 8746
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: How to merge a nodes from two different xml files using DOM library
« Reply #1 on: February 25, 2018, 08:01:42 am »
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}{$H+}
  2.  
  3. uses
  4.   Classes, SysUtils, DOM, XMLRead, XMLWrite;
  5.  
  6. const
  7.   XMLHeader = '<?xml version="1.0"?>';
  8.  
  9. var
  10.   ss1,ss2: TStringStream;
  11.   xml1,xml2: TXMLDocument;
  12.   node,impNode: TDOMNode;
  13. begin
  14.   try
  15.     ss1 := TStringStream.Create(XMLHeader + '<root><node attr="value">text</node></root>');
  16.     ss2 := TStringStream.Create(XMLHeader + '<root></root>');
  17.  
  18.     WriteLn('BEFORE:');
  19.     WriteLn('XML 1: ' + ss1.DataString);
  20.     WriteLn('XML 2: ' + ss2.DataString);
  21.  
  22.     ReadXMLFile(xml1,ss1);
  23.     ReadXMLFile(xml2,ss2);
  24.  
  25.     node := xml1.DocumentElement.FirstChild;   // xm1.root.node
  26.     impNode := xml2.ImportNode(node,true);     // import a.k.a clone + assign new owner document
  27.     xml2.DocumentElement.AppendChild(impNode); // make it a new child of xml2.root
  28.     xml1.DocumentElement.RemoveChild(node);    // remove from xml1.root
  29.  
  30.     // stream position will be at the string end after ReadXMLFile above, so we need to
  31.     // reset it to the initial position, otherwise it will be appended instead of overwritten
  32.     ss1.Seek(0, soBeginning);
  33.     ss2.Seek(0, soBeginning);
  34.     WriteXMLFile(xml1,ss1);
  35.     WriteXMLFile(xml2,ss2);
  36.  
  37.     WriteLn();
  38.     WriteLn('AFTER:');
  39.     WriteLn('XML 1: ' + ss1.DataString);
  40.     WriteLn('XML 2: ' + ss2.DataString);
  41.   finally
  42.     xml1.Free;
  43.     xml2.Free;
  44.     ss1.Free;
  45.     ss2.Free;
  46.   end;
  47. end.
  48.  
Merging is just a variation of this, I'll leave that as an exercise for you.
« Last Edit: February 25, 2018, 08:03:14 am by Leledumbo »

 

TinyPortal © 2005-2018