DelphiでxmlファイルをGridに読み込む。 type TxmlForm = class(TForm) xd: TXMLDocument; Grid: TStringGrid; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; OpenButton: TButton; SaveButton: TButton; procedure OpenButtonClick(Sender: TObject); procedure SaveButtonClick(Sender: TObject); private { Private 宣言 } FNodeName: string; FRowIndex, FColIndex: Integer; procedure AddChildren(xmlNode: IXMLNode); public { Public 宣言 } end; var xmlForm: TxmlForm; implementation {$R *.dfm} procedure TxmlForm.OpenButtonClick(Sender: TObject); var i, j: Integer; begin if not OpenDialog.Execute then Exit; for i := 0 to Grid.ColCount - 1 do Grid.Cols[i].Clear; Grid.RowCount := 2; FRowIndex := 1; FColIndex := 1; for i := 0 to OpenDialog.Files.Count - 1 do begin xd.FileName := OpenDialog.Files[i]; xd.Active := True; AddChildren(xd.Node); for j := 0 to Grid.ColCount - 1 do if Grid.Cells[j, FRowIndex] = '' then Grid.Cells[j, FRowIndex] := Grid.Cells[j, FRowIndex - 1]; Grid.Cells[0, FRowIndex] := IntToStr(FRowIndex); end; Grid.ColCount := FColIndex; Grid.RowCount := FRowIndex + 1; end; procedure TxmlForm.SaveButtonClick(Sender: TObject); var Row, Col: Integer; s: string; begin if not SaveDialog.Execute then Exit; s := ''; for Row := 0 to Grid.RowCount - 1 do begin for Col := 1 to Grid.ColCount - 1 do s := s + AnsiQuotedStr(Grid.Cells[Col, Row], '"') + ','; s[Length(s)] := #13; s := s + #10; end; StrToFile(s, SaveDialog.FileName, nil); end; procedure TxmlForm.AddChildren(xmlNode: IXMLNode); var i, j, ColIndex: Integer; s: string; begin for i := 0 to xmlNode.ChildNodes.Count - 1 do begin if xmlNode.ChildNodes[i].NodeType = ntText then begin s := xmlNode.ChildNodes[i].NodeValue; ColIndex := Grid.Rows[0].IndexOf(FNodeName); if ColIndex < 0 then begin Grid.Cells[FColIndex, 0] := FNodeName; ColIndex := FColIndex; Inc(FColIndex); end; if Grid.Cells[ColIndex, FRowIndex] = '' then Grid.Cells[ColIndex, FRowIndex] := s else begin for j := 0 to Grid.ColCount - 1 do if Grid.Cells[j, FRowIndex] = '' then Grid.Cells[j, FRowIndex] := Grid.Cells[j, FRowIndex - 1]; Grid.Cells[0, FRowIndex] := IntToStr(FRowIndex); Inc(FRowIndex); Grid.Cells[ColIndex, FRowIndex] := s end; end else begin FNodeName := xmlNode.ChildNodes[i].NodeName; end; AddChildren(xmlNode.ChildNodes[i]); end; end;
2010年01月28日
Delphi:xmlをGridに読み込む
この記事へのコメント
コメントを書く
この記事へのトラックバック