我有一个使用OmniXML的Delphi程序加载的xml文档。如何用xml字符串定义的新节点替换特定节点?
或者,换句话说,我如何编辑节点的xml表示并应用这些更改?类似于XMLNode.SetXML(NewXML:String):
XMLNode.SetXML('<Test><TestNode>This is a test</TestNode></Test>');发布于 2014-01-29 03:42:00
我无法找到一种方法将现有的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>https://stackoverflow.com/questions/21403546
复制相似问题