[英]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? 如何使用Delphi搜索和替换XML文件中的标记值?
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. 我知道XML标签是什么,但是值是随机的,只需要重置为默认值,所以实际上我不能/不应该搜索值而只搜索标签。 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? 我是Delphi的新手,有人能为我提供一个如何做到这一点的简单示例吗?
Thank you in advance. 先感谢您。
I'd load the XML file using Delphi's IXMLDocument
and use the document to replace the element. 我使用Delphi的
IXMLDocument
加载XML文件,并使用该文档替换元素。 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: 最好的可能是使用XML解析器 ,例如:
If it is a rather small XML file, you could also just load the XML into a string(list) and use a regular expression : 如果它是一个相当小的XML文件,您也可以只将XML加载到字符串(列表)中并使用正则表达式 :
var
Regex: TPerlRegEx;
Regex := TPerlRegEx.Create(nil);
Regex.RegEx := '<yourtag>.*?</yourtag>';
Result := objRegEx.Replace(inputString, replacementString, true);
You can get the TPerlRegex component here . 您可以在此处获取TPerlRegex组件。
The third way would include doing all the dirty work by hand , using pos , delete and insert . 第三种方式包括手工完成所有脏工作,使用pos , delete和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).
你必须找到开始和结束标记的两个pos'es和开放标记的>的pos,删除这两个索引之间的字符串,然后插入你的默认值(你必须迭代如果有多个匹配则匹配所有匹配项)。 Not the way I would prefer ;-)
不是我喜欢的方式;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.