我尝试向 XML 文件的序言中添加一些属性,但除了在删除旧序言后插入完整的序言字符串之外,我找不到其他方法来实现此目的
以下示例显示了发生的情况:
const
XML_Template = 'Invoice_%s.xml';
var
inv: IXMLInvoiceWood;
XMLFile: string;
sl: TStringList;
begin;
XMLFile := format(XML_Template, ['ABC-123']);
inv := NewInvoiceWood;
inv.OwnerDocument.SaveToFile(XMLFile);
try
sl := TStringList.Create;
sl.LoadFromFile(XMLFile);
sl[0] := '<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="InvoiceWoodV2R31_Build20081207.xsl" type="text/xsl"?>';
sl.SaveToFile(XMLFile);
finally
sl.Free;
end;
inv := LoadInvoiceWood(XMLFile);
inv.OwnerDocument.SaveToFile(XMLFile); // <<<<--- here it splits the line
mmo1.Lines.LoadFromFile(XMLFile);
保存到时线会分开:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="InvoiceWoodV2R31_Build20081207.xsl" type="text/xsl"?>
这是一个错误还是我在这里做错了什么?
许多 XML 实现都会生成格式化输出,除非您另外指定。这是正常行为。
无论如何,添加额外属性的正确方法是使用 XML DOM 接口将它们插入文档本身,您不需要在生成 XML 文本后对其进行操作。
IXMLDocument
具有 Encoding
和 Version
属性,以及可以创建处理指令(CreateNode()
)的 <?...?>
方法,例如:
const
XML_Template = 'Invoice_%s.xml';
var
inv: IXMLInvoiceWood;
XMLFile: string;
instr: IXMLNode;
begin;
XMLFile := Format(XML_Template, ['ABC-123']);
inv := NewInvoiceWood;
inv.OwnerDocument.Version := '1.0';
inv.OwnerDocument.Encoding := 'UTF-8';
instr := inv.OwnerDocument.CreateNode('xml-stylesheet', ntProcessingInstr, 'href="InvoiceWoodV2R31_Build20081207.xsl" type="text/xsl"');
inv.OwnerDocument.ChildNodes.Add(instr);
// add DocumentElement and other nodes as needed...
inv.OwnerDocument.SaveToFile(XMLFile);
mmo1.Lines.LoadFromFile(XMLFile);