如何在OmniXML中替换节点xml?

时间:2014-01-28 10:49:45

标签: xml delphi

我有一个使用OmniXML由我的Delphi程序加载的xml文档。如何用xml string定义的新节点替换特定节点?

或者,换句话说,如何编辑节点的xml表示并应用更改? 像XMLNode.SetXML(NewXML:String):

XMLNode.SetXML('<Test><TestNode>This is a test</TestNode></Test>');

1 个答案:

答案 0 :(得分:0)

我找不到用新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>