views:

372

answers:

2

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.

+5  A: 

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


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 ;-)

Mef
regular expressions usually have the drawback that they don't take picularities of the underlying text format into account (for instance, look at the wealth of "validate-email-address-using-regex"). So, I'd suggest you put the XML Parser possibility in your answer first.
Jeroen Pluimers
I agree... done.
Mef
+1; Thanks for editing.
Jeroen Pluimers
+6  A: 

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;
Phil Ross