【发布时间】:2013-08-23 11:55:56
【问题描述】:
我正在将配置数据写入 XML 文件。但是XML看起来很不结构化或者怎么说
<Configuration>
<Ftp Host="LOCALHOST" Port="21"/>
<Pop3 Host="LOCALHOST" Port="110" Interval="30000"/>
<Smtp Host="LOCALHOST" Port="25"/>
</Configuration>
我希望它看起来像
<Configuration>
<Ftp
Host="LOCALHOST"
Port="21"
/>
<Pop3
Host="LOCALHOST"
Port="110"
Interval="30000"
/>
<Smtp
Host="LOCALHOST"
Port="25"
/>
</Configuration>
有没有可能 这是我的 Delphi 代码的 sn-p。我有所有类型的函数/程序,但这里只显示 2 个
constructor TConnXml.Create(const FileName: string);
begin
inherited Create;
fConfigfile := FileName;
fXMLDoc := TXMLDocument.Create(Application);
fXMLDoc.Options := [doNodeAutoIndent];
if FileExists(fConfigfile) then
fXMLDoc.LoadFromFile(fConfigfile)
else
begin
fXMLDoc.Active := True;
fXMLDoc.AddChild('Configuration');
fXMLDoc.SaveToFile(fConfigfile);
end;
end;
constructor TConnXml.Create;
begin
Create(SettingsFileBuild);
end;
function TConnXml.ReadString(const Section, Key, Default: string): string;
var
Node: IXMLNode;
begin
Node := fXMLDoc.DocumentElement.ChildNodes.FindNode(Section);
if Assigned(Node) and Node.HasAttribute(Key) then
Result := Node.Attributes[Key]
else
Result := Default;
end;
procedure TConnXml.WriteString(const Section, Key, Value: string);
var
Node: IXMLNode;
begin
if ReadString(Section, Key, '') = Value then
Exit;
Node := fXMLDoc.DocumentElement.ChildNodes.FindNode(Section);
if not Assigned(Node) then
Node := fXMLDoc.DocumentElement.AddChild(Section);
Node.Attributes[Key] := Value;
fModified := True;
Save;
end;
procedure TConnXml.Save;
begin
if not fModified then
Exit;
if fBackup then
CopyFile(PChar(fConfigfile), PChar(fConfigfile + '.bak'), False);
fXMLDoc.Active := True;
fXMLDoc.SaveToFile(fConfigfile);
fModified := False;
end;
function TConnXml.ReadBoolean(const Section, Key: string; Default: Boolean): Boolean;
begin
Result := Boolean(ReadInteger(Section, Key, Integer(Default)));
end;
procedure TConnXml.WriteBoolean(const Section, Key: string; Value: Boolean);
begin
WriteInteger(Section, Key, Integer(Value));
end;
【问题讨论】:
-
xml 的主要目的不是供人类阅读。它用于机器与机器之间的通信。您的输出应该是“正确”格式的 XML 输出。为什么你需要另一个外表?如果您真的希望它“看起来”不是 xml,您必须编写自己的 XmlWriter,或者您应该更改为其他格式。
-
考虑改用TIniFile。编辑
.ini文件结构中的设置的人不太可能出错,而 XML 是 syntax-heavy。 -
改用 YAML 让它看起来更好
-
它看起来像格式完美的 XML,具有标准格式(甚至带有特殊的缩进以使其易于阅读)。您可以将 XSL(T) 样式表与它相关联,将其转换为漂亮的 HTML 表示,因此它在浏览器中看起来很整洁。但这可能是矫枉过正。
-
您已经使用了 doNodeAutoIndent 选项,它使 XML 可读。绰绰有余。
标签: xml delphi xml-formatting