我找不到用新 XML 实际替换节点的现有 XML 的方法(特别是如果该 XML 具有多个级别节点)。
不过,我确实想出了如何完成你想做的事情。
- 为您的新 XML 内容创建一个新的临时 XML 文档
- 在现有 XML 结构中创建一个新节点作为拥有要替换的节点的父节点的子节点。
- 将临时 XML 文档中的节点复制到新创建的子节点中。
- 删除原始节点并将其替换为您创建的新子节点(使用父节点的
ReplaceNode)。
这是一个快速示例控制台应用程序,它使用以下 XML 开头(保存在我机器上的本地文件夹中的 test.xml 中)。 XML 文件包含此内容(为简洁起见,我省略了 XML 处理指令,但代码也可以使用它):
<AddInList>
<AddInItem>
<Title>Original title</Title>
<Description>Original description</Description>
</AddInItem>
</AddInList>
代码:
program XMLReplaceNodeContent;
{$APPTYPE CONSOLE}
uses
SysUtils,
OmniXML,
OmniXMLUtils;
var
XMLDoc: IXMLDocument;
TempDoc: IXMLDocument;
OldNode, NewNode, NodeToDelete: IXMLNode;
const
XMLFile = 'e:\tempfiles\Test.xml';
NewXML = '<AddInItem>' +
'<Title>This is a test node</Title>' +
'<Description>New description</Description>' +
'</AddInItem>';
begin
XMLDoc := CreateXMLDoc;
// Turn off any formatting. We'll add it back later, if you want
XMLDoc.PreserveWhiteSpace := False;
XMLDoc.Load(XMLFile);
TempDoc := CreateXMLDoc;
TempDoc.PreserveWhiteSpace := False;
TempDoc.LoadXML(NewXML);
XMLDoc.SelectSingleNode('AddInList', OldNode);
OldNode.SelectSingleNode('AddInItem', NodeToDelete);
// Create replacement node(s) from new XML
NewNode := XMLDoc.CreateElement('AddInItem');
// Copy replacement nodes to new node of original XML
CopyNode(TempDoc.DocumentElement, NewNode, True);
// Replace the original node with the new node
OldNode.ReplaceChild(NewNode, NodeToDelete);
// To prevent formatting of XML, comment this line and
// uncomment the next one
XMLSaveToFile(XMLDoc, XMLFile, ofIndent);
// XMLDoc.Save(XMLFile);
Writeln('XML with replace node saved successfully');
Readln;
end.
Test.xml中的最终输出:
<AddInList>
<AddInItem>
<Title>This is a test node</Title>
<Description>New description</Description>
</AddInItem>
</AddInList>