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.
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;
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With