如何在 XML 文档中写入 1 行以上

问题描述 投票:0回答:1

我正在尝试将记录数组中的

word
boolean
值保存到 XML 文档中。这是我的代码:

procedure AddArrayToXMLFile(const Array : array of TKeycodeRecord; const Name : string);
var
  XMLFile : IXMLDocument;
  NameNode, ArrayFieldNode: IXMLNode;
  i : integer;
begin
  if FileExists(ArrayXMLFilePath) then
  begin
    XMLFile := LoadXMLDocument(ArrayXMLFilePath);
  end
  else
  begin
    XMLFile := NewXMLDocument;
    NameNode := XMLFile.AddChild(Name);
    ArrayFieldNode := NameNode.AddChild('child');
  end;

  for i := 0 to Length(Array) - 1 do
  begin
    ArrayFieldNode.Attributes['keycode'] := Array[i].keycode;
    ArrayFieldNode.Attributes['shiftState'] := Array[i].shiftState;
  end;

  XMLFile.SaveToFile(ArrayXMLFilePath);
end;

这就是结果:

<?xml version="1.0"?>
<TestName><child keycode="48" shiftState="false"/></TestName>

该过程仅保存数组的最后一个条目,这使我相信

for loop
仅更改第一个条目的值,而不是添加新行。我想添加新行并将数组的所有行保存为 XML 文档中的值。想要的结果看起来像这样,但有更多条目:

<?xml version="1.0"?>
<TestName><child keycode="52" shiftState="false"/></TestName>
<TestName><child keycode="70" shiftState="true"/></TestName>
<TestName><child keycode="75" shiftState="false"/></TestName>
<TestName><child keycode="49" shiftState="false"/></TestName>
<TestName><child keycode="48" shiftState="false"/></TestName>
xml delphi delphi-2007
1个回答
0
投票

您需要在 for 循环中添加节点 NameNodeArrayFieldNode,如下所示:

procedure AddArrayToXMLFile(const Array : array of TKeycodeRecord; const Name : string);
var
  XMLFile : IXMLDocument;
  NameNode, ArrayFieldNode: IXMLNode;
  i : integer;
begin
  if FileExists(ArrayXMLFilePath) then
  begin
    XMLFile := LoadXMLDocument(ArrayXMLFilePath);
  end
  else
  begin
    XMLFile := NewXMLDocument;
  end;

  for i := 0 to Length(Array) - 1 do
  begin
    NameNode := XMLFile.AddChild(Name);
    ArrayFieldNode := NameNode.AddChild('child');
    ArrayFieldNode.Attributes['keycode'] := Array[i].keycode;
    ArrayFieldNode.Attributes['shiftState'] := Array[i].shiftState;
  end;

  XMLFile.SaveToFile(ArrayXMLFilePath);
end;

您所做的方法是添加一个节点,然后在循环中在每次迭代中更改同一节点的属性。

© www.soinside.com 2019 - 2024. All rights reserved.