2008-10-24 24 views
15

任何人都有一個現成的函數,將採取一個XML字符串並返回一個正確的縮進字符串?不錯的代碼來格式化XML字符串

<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML> 

,並會插入換行和製表符或空格後返回的回報很好格式的字符串?

回答

10

使用OmniXML

program TestIndentXML; 

{$APPTYPE CONSOLE} 

uses 
    SysUtils, 
    OmniXML, 
    OmniXMLUtils; 

function IndentXML(const xml: string): string; 
var 
    xmlDoc: IXMLDocument; 
begin 
    Result := ''; 
    xmlDoc := CreateXMLDoc; 
    if not XMLLoadFromAnsiString(xmlDoc, xml) then 
    Exit; 
    Result := XMLSaveToAnsiString(xmlDoc, ofIndent); 
end; 

begin 
    Writeln(IndentXML('<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>')); 
    Readln; 
end. 

上面的代碼片段被釋放到公共領域。

4

使用XSLT ...

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output method="xml" indent="yes" /> 
    <xsl:template match="/"> 
     <xsl:copy-of select="."/> 
    </xsl:template> 
</xsl:stylesheet> 
+0

PS - 這將摺疊。 – dacracot 2008-10-25 21:43:33

1

XML文檔DOM對象建成德爾福有一個漂亮的格式化選項。您只需將XML加載到其中並將其保存回去,如果您設置了該選項,那麼它就會變得非常漂亮。

我會查找並更新此答案。

+0

你應該在回答前查看它:) – 2008-10-25 10:48:53

+0

不要總是有時間,但它本來不錯。 – 2008-10-25 23:26:47

4

我已經使用了Tidy和來自MichaelElsdörfer的libtidy。它給你提供了大量的選項,你可以在應用程序外部配置它們。也適用於HTML。

這是我使用的一些非常粗略的代碼。按照你的喜好去做。

function TForm1.DoTidy(const Source: string): string; 
var 
    Tidy    : TLibTidy; 
begin 
    if not TidyGlobal.LoadTidyLibrary('libtidy.dll') then 
    begin 
    // Application.MessageBox('TidyLib is not available.', 'Error', 16); 
    // exit; 
    raise Exception.Create('Cannot load TidyLib.dll'); 
    end; 
    Tidy := TLibTidy.Create(Self); 
    try 
    Tidy.LoadConfigFile(ExtractFilePath(Application.ExeName) + 
     'tidyconfig.txt'); 
    // Tidy.Configuration.IndentContent := tsYes; 
    // Tidy.Configuration.IndentSpaces := 5; 
    // Tidy.Configuration.UpperCaseTags := False; 
    // Tidy.Configuration.NumEntities := True; 
    // Tidy.Configuration.AccessibilityCheckLevel := 2; 
    // Tidy.Configuration.InlineTags := 'foo,bar'; 
    // Tidy.Configuration.XmlDecl := True; 
    // Tidy.Configuration.XmlTags := True; 
    // Tidy.Configuration.CharEncoding := TidyUTF8; 
    // Tidy.Configuration.WrapLen := 0; 
    // Tidy.SaveConfigFile('tidyconfig.txt'); 
    Tidy.ParseString(Source); 
    Result := Tidy.RunDiagnosticsAndRepair; 
    finally 
    Tidy.Free; 
    end; 
end;