windows7
windows7

Reputation: 51

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.

Upvotes: 5

Views: 6869

Answers (2)

Leo
Leo

Reputation: 38190

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

Upvotes: 6

Phil Ross
Phil Ross

Reputation: 26100

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;

Upvotes: 9

Related Questions