2

我正在使用 Delphi 7 和 OmniXML 并尝试创建一个文档,我需要 DocumentElement 为:

<?xml 版本="1.0" 编码="UTF-8"?>

但我不明白如何添加最后一个?标志。

我的代码:

var    
  xml: IXMLDocument;   
begin    
  xml := ConstructXMLDocument('?xml');    
  SetNodeAttr(xml.DocumentElement, 'version', '1.0');   
  SetNodeAttr(xml.DocumentElement, 'encoding', 'UTF-8');    
  XMLSaveToFile(xml, 'C:\Test1.xml', ofIndent);  
end;
4

1 回答 1

6
<?xml version="1.0" encoding="UTF-8"?>

这不是Document Element。它甚至不是一个元素,而是一个处理指令,它恰好是 XML 声明,有时也称为 XML 序言。

要指定 XML 声明的属性,请改用:

xmlDoc.CreateProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"');

例如:

{$APPTYPE CONSOLE}

uses
  OmniXML;

var
  XMLDoc: IXMLDocument;
  ProcessingInstruction: IXMLProcessingInstruction;
  DocumentElement: IXMLElement;
begin
  XMLDoc := CreateXMLDoc;
  ProcessingInstruction := XMLDoc.CreateProcessingInstruction('xml',
    'version="1.0" encoding="UTF-8"');
  DocumentElement := XMLDoc.CreateElement('foo');

  XMLDoc.DocumentElement := DocumentElement;
  XMLDoc.InsertBefore(ProcessingInstruction, DocumentElement);

  XMLDoc.Save('foo.xml', ofIndent);
end.
于 2017-01-09T15:59:52.083 回答