I have an xml document loaded by my Delphi program using OmniXML. How can I replace a specific node with a new one defined by xml string?
Or, in other words, how can I edit xml representation of a node and apply the changes? Something like XMLNode.SetXML(NewXML:String):
XMLNode.SetXML('<Test><TestNode>This is a test</TestNode></Test>');
I can't find a way to actually replace the existing XML for a node with new XML (especially if that XML has multiple level nodes).
I did figure out how to accomplish what you want to do, however.
ReplaceNode
). Here's a quick example console app that does just that, using the following XML to start with (saved in test.xml
in a local folder on my machine). The XML file contains this content (I've omitted the XML processing instruction for brevity, but the code works with it as well):
<AddInList>
<AddInItem>
<Title>Original title</Title>
<Description>Original description</Description>
</AddInItem>
</AddInList>
The code:
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.
The final output in Test.xml
:
<AddInList>
<AddInItem>
<Title>This is a test node</Title>
<Description>New description</Description>
</AddInItem>
</AddInList>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.