Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search and replace a tag value in xml file using delphi?

How to search and replace a tag value in XML file using Delphi?

I know what the XML tag is, but the value is random and simply needs to be reset to a default value, so in reality I cannot/should not search for the value but only the tag. I also know the location of the file/files.

I'm new to Delphi, can someone provide me a simply example on how this could be done?

Thank you in advance.

like image 840
windows7 Avatar asked Jan 19 '10 09:01

windows7


2 Answers

I'd load the XML file using Delphi's IXMLDocument and use the document to replace the element. Something like this:

uses
  XMLDoc,
  XMLIntf;

procedure ChangeTag(const filename : String);
var
  doc : IXMLDocument;
  parent : IXMLNode;
  toReplace : IXMLNode;
  replacement : IXMLNode;
begin
  doc := LoadXMLDocument(filename);

  parent := doc.DocumentElement.ChildNodes.FindNode('parent');
  toReplace := parent.ChildNodes.FindNode('toReplace');

  replacement := doc.CreateElement('replacement', '');
  replacement.Text := toReplace.Text;

  parent.ChildNodes.ReplaceNode(toReplace, replacement);

  doc.SaveToFile(filename);
end;
like image 183
Phil Ross Avatar answered Nov 11 '22 07:11

Phil Ross


The best possibility is using an XML parser, for instance:

  • http://www.icom-dv.de/products/xml_tools/uk_xml_parser_01.php3
  • http://www.omnixml.com/
  • http://www.destructor.de/xmlparser/index.htm
  • http://www.simdesign.nl/xml.html
  • ... many more, just Google it ;-)

If it is a rather small XML file, you could also just load the XML into a string(list) and use a regular expression:

var
  Regex: TPerlRegEx;

Regex := TPerlRegEx.Create(nil);
Regex.RegEx := '<yourtag>.*?</yourtag>';
Result := objRegEx.Replace(inputString, replacementString, true);

You can get the TPerlRegex component here.


The third way would include doing all the dirty work by hand, using pos, delete and insert. You would have to find the two pos'es of the opening and ending tag and the pos of the > for the openeing tag), delete the string between those two indexes, and insert your default value afterwards (and you would have to iterate over all matches if there are more than one occurrences). Not the way I would prefer ;-)

like image 36
Leo Avatar answered Nov 11 '22 05:11

Leo