1

Hi i have an xml like this

<?xml version="1.0" encoding="UTF-8"?>
    <receipt>
        <item></item>
        <vat></vat>
        <body>
        <details>
            <description>a</description>
            <price></price>
        </details>
        <details>
            <description>b</description>
            <price></price>
        </details>
        </body>
    </receipt>

where details describe a single line of a receipt.

i need to read all details.

i tried with this code:

EntryNode := xmldocument1.DocumentElement.ChildNodes['details'];
for i := 0 to EntryNode.ChildNodes.Count do 
begin
  text := EntryNode.ChildNodes[i];
  Break;
end;

but i obtain only the first details tag.

how can i edit my code?

4

2 回答 2

4

读取/导入

   procedure importXml;
    var
      i: Integer;
      TransUnits: IXMLNodeList;
    begin
      ListBox.Clear;
      XMLDocument.LoadFromFile('C:\yourpath\demo.xml');
      if Assigned(XMLDocument) then
      begin
        TransUnits  := XMLDocument.DocumentElement.ChildNodes['file'].ChildNodes['body'].ChildNodes;

        for i := 0 to TransUnits.Count - 1 do
          ListBox.Items.Add(TransUnits[I].Attributes['id'] + ' ' + TransUnits[i].ChildNodes['source'].Text + ' ' + TransUnits[i].ChildNodes['target'].Text );
      end;
      XMLDocument.Active;
    end;

查看我的工作示例代码。

写入/导出

procedure WriteExport(Sender: TObject);
var
  source, target: String;
  TargetNode: IXMLNode;
  TransUnits: IXMLNodeList;
begin
  //XMLDocument.Encoding := 'UTF8';
  target := edTarget.Text;
  TransUnits  := XMLDocument.DocumentElement.ChildNodes['file'].ChildNodes['body'].ChildNodes;

  TargetNode := TransUnits[ListBox.ItemIndex].ChildNodes.FindNode('target');

  //if not Assigned(TargetNode) then
  //  TargetNode := XMLDocument.DocumentElement.ChildNodes['file'].ChildNodes['body'].ChildNodes[ListBox.ItemIndex].AddChild('target'); Create

  TargetNode.Text := target;
  XMLDocument.SaveToFile('C:\export\demo.xml');
end;
于 2013-06-07T09:46:51.160 回答
3

您将不得不循环并检查 ChildNodes 是否是

var
 OuterRoot,EntryNode:IXmlNode;
 i,j:Integer;
begin
OuterRoot := xmldocument1.DocumentElement;
for i := 0 to OuterRoot.ChildNodes.Count -1 do
  begin
    if OuterRoot.ChildNodes[i].NodeName='details' then
      begin
        Memo1.Lines.Add(StringOfChar('-',20));
        Memo1.Lines.Add(OuterRoot.ChildNodes[i].NodeName +':');
        EntryNode := OuterRoot.ChildNodes[i];
        for j := 0 to EntryNode.ChildNodes.Count -1 do
        begin
          Memo1.Lines.Add( EntryNode.ChildNodes[j].NodeName + '-'  + EntryNode.ChildNodes[j].Text);
        end;
      end;
  end;
end;
于 2013-06-07T09:50:31.387 回答